int _tmain(int argc, _TCHAR* argv[]){
long long nData = 143336600;
char arrChar[8+2];
int nRet = sprintf_s(arrChar,8+2,"%lld",nData);
char* pData;
pData = arrChar;
return 0;
}
上面这段代码能够在VS2010中正常运行,其中nRet == 9;
但是,当8+2改成8+1的时候,就会报buffer too small 的异常
请问这个情况怎么解释?
sprintf_s returns the number of bytes stored in buffer, not counting the terminating null character. swprintf_s returns the number of wide characters stored in buffer, not counting the terminating null wide character.
There are nine visible characters in total, and 10 bytes need to be allocated to include the trailing '0';
Pay attention to the third to fifth lines
Not familiar with C++, but I checked the official documentation
The parameter description is as follows. The first parameter buffer is the output storage location, and the second parameter sizeOfBuffer is the maximum allowed number of characters. Therefore, if you want to change it here, you need to ensure that the length of arrChar is the same as the value of the second parameter. , and also ensure that the length of the fourth parameter nData cannot be greater than the length of sizeOfBuffer, which is 8+1.
Regarding this issue, in fact, my original intention is to store the 8-byte value in a byte array for easy transmission;
So actually just use memory copy,
but I use With a conversion function like sprintf_s, its function is actually to copy the literal value of the value into a string. That is to say, the ASCII code of each digit of the value in the memory is not the binary representation of the value.
Copy the value into a string. The string is of variable length and will increase as the number of numbers increases.