0

While playing around with sprintf to figure out how to make it work before adding it to my recover.c code, I ran into a weird (at least for me) situation.

I declare a counter variable (int type), use this variable as an argument for sprintf and, as far as I can tell, successfully create a filename using the output of sprintf. However, when I printf the value of my counter variable (for sanity check), the value of my counter variable has been modified to a super-long number... It is unclear to me WHY sprintf has any effect on the counter and how I can return the counter to be what it used to be (e.g., to add 1 in order to rename the next file appropriately.

My test code is available in this link. Any input will be greatly appreciated!

1 Answer 1

1

The problem lies in your declaration of imagenr.

char imagenr = 0;

This creates a variable that holds a single character, not a string. Later, with the sprintf() call, the code copies an 8 char string (7 chars + end of string marker) into that variable, which overwrites adjacent memory. That adjacent memory looks to be the variable n.

You need to declare a character array large enough to handle the content. Remember, once declared a char string var's size can't be changed.

char imagenr[8];
sprintf(imagenr,"%'.3i.jpg", n);

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .