I have a funny problem using this function. I use it as follow:
int nSeq = 1;
char cBuf[8];
int j = sprintf_s(cBuf, sizeof(cBuf), "%08d", nSeq);
And every time I get an exception. The exception is buffer to small. When I changed the second field in the function to sizeof(cBuf) + 1.
Why do I need to add one if I only want to copy 8 bytes and I have an array that contains 8 bytes?
The sprintf_s function formats and stores a series of characters and values in buffer . Each argument (if any) is converted and output according to the corresponding format specification in format . The format consists of ordinary characters and has the same form and function as the format argument for printf .
The snprintf function The main difference between snprintf and sprintf is that the former takes an argument that specifies the number of characters to write to the character array, whereas the latter does not take such an argument.
Your buffer contains 8 places. Your string contains 8 characters and a null character to close it.
Your string will require terminating '\0' and 8 bytes of data(00000001) due to %08d. So you have to size as 9.
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