I'm having an issue with sprintf in C resetting the value of a counter variable when I run it. Here in a nutshell is what is happening:
int count = 0;
count++;
printf("%d\n", count); // count will equal 1
char title[7];
sprintf(title, "%.3d.jpg", count);
printf("%d\n", count); // count now equals 0 again
Is this normal behavior for sprintf?
sprintf stands for "string print". In C programming language, it is a file handling function that is used to send formatted output to the string. Instead of printing on console, sprintf() function stores the output on char buffer that is specified in sprintf.
sprintf() in C int sprintf(char *str, const char *string,...); Return: If successful, it returns the total number of characters written excluding null-character appended in the string, in case of failure a negative number is returned . sprintf stands for “String print”.
The sscanf () function and the sprintf () function are like the two sides of a coin. You can now use the sprintf() function to reassemble the string. You can use the same char array stringa- its previous value gets overwritten.
The sprintf function returns the number of characters stored in the array s , not including the terminating null character. The behavior of this function is undefined if copying takes place between objects that overlap—for example, if s is also given as an argument to be printed under control of the ' %s ' conversion.
title
is too small, sprintf is writing beyond the bounds of title
, and writing into count
, corrupting its value.
Note that title
needs to be long at least 8 bytes: 3 for %.3d
, 4 for .jpg
and 1 for the terminator \0
.
As Grijesh Chauhan points out, you can make sure that you never write beyond the allocated size of the string by using snprintf
, i.e.:
char title[8];
snprintf(title, sizeof(title), "%.3d.jpg", count);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With