Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write into a char array in C at specific location using sprintf?

I am trying to port some code written in MATLAB to C, so that I can compile the function and execute it faster (the code is executed very often and it would bring a significant speed increase).

So basically what my MATLAB code does it that it takes a matrix and converts it to a string, adding brackets and commas, so I can write it to a text file. Here's an idea of how this would work for a vector MyVec:

MyVec = rand(1,5);
NbVal = length(MyVec)
VarValueAsText = blanks(2 + NbVal*30 + (NbVal-1));
VarValueAsText([1 end]) = '[]';
VarValueAsText(1 + 31*(1:NbVal-1)) = ',';
for i = 1:NbVal
   VarValueAsText(1+(i-1)*31+(1:30)) = sprintf('%30.15f', MyVec(i));
end

Now, how can I achieve a similar result in C? It doesn't seem too difficult, since I can calculate in advance the size of my string (char array) and I know the position of each element that I need to write to my memory area. Also the sprintf function exists in C. However, I have trouble understanding how to set this up, also because I don't have an environment where I can learn easily by trial and error (for each attempt I have to recompile, which often leads to a segmentation fault and MATLAB crashing...).

I hope someone can help even though the problem will probably seem trivial, but I have have very little experience with C and I haven't been able to find an appropriate example to start from...

like image 622
Federico Avatar asked Mar 14 '26 03:03

Federico


2 Answers

Given an offset (in bytes) into a string, retrieving a pointer to this offset is done simply with:

char *ptr = &string[offset];

If you are iterating through the lines of your matrix to print them, your loop might look as follow:

char *ptr = output_buffer;
for (i = 0; i < n_lines; i++) {
    sprintf (ptr, "...", ...);
    ptr = &ptr[line_length];
}

Be sure that you have allocated enough memory for your output buffer though.

like image 75
Yno Avatar answered Mar 16 '26 18:03

Yno


Remember that sprintf will put a string-terminator at the end of the string it prints, so if the string you "print" into should be longer than the string you print, then that won't work.

So if you just want to overwrite part of the string, you should probably use sprintf to a temporary buffer, and then use memcpy to copy that buffer into the actual string. Something like this:

char temp[32];
sprintf(temp, "...", ...);

memcpy(&destination[position], temp, strlen(temp));
like image 38
Some programmer dude Avatar answered Mar 16 '26 17:03

Some programmer dude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!