search

Home  >  Q&A  >  body text

c++ - sprintf_s第二个参数的设置问题?

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 的异常
请问这个情况怎么解释?

巴扎黑巴扎黑2807 days ago685

reply all(3)I'll reply

  • 天蓬老师

    天蓬老师2017-04-17 15:18:43

    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';

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 15:18:43

    Pay attention to the third to fifth lines

    char arrChar[8+2];
    int nRet = sprintf_s(arrChar,8+2,"%lld",nData);
    

    Not familiar with C++, but I checked the official documentation

    int sprintf_s(
       char *buffer,
       size_t sizeOfBuffer,
       const char *format [,
          argument] ... 
    );
    

    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.

    reply
    0
  • PHPz

    PHPz2017-04-17 15:18:43

    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.

    reply
    0
  • Cancelreply