首頁  >  問答  >  主體

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

巴扎黑巴扎黑2715 天前640

全部回覆(3)我來回復

  • 天蓬老师

    天蓬老师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 of wide characters stored in buffer, not counting the terminating null wide character.<>

    總共九個可見字符,需要分配10個位元組長度,用來包含結尾的'0';

    回覆
    0
  • 天蓬老师

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

    注意一下第三行到第五行

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

    不熟悉C++,但是查了一下官方文檔

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

    參數說明是這樣的,第一個參數buffer是輸出儲存位置,第二個參數sizeOfBuffer是最大允許的字元數,因此,這裡要改的話需要確保arrChar的長度和第二個參數的值一樣,同時也要確保第四個參數nData的長度不能大於sizeOfBuffer的長度,也就是8+1。

    回覆
    0
  • PHPz

    PHPz2017-04-17 15:18:43

    關於這個問題,其實我的本意,只是想把8位元組表示的數值,用位元組數組存儲,方便傳輸;
    所以其實只用內存拷貝就可以了,
    可是我用了sprintf_s這樣的轉換函數,它的作用其實是將該數值的字面值拷貝到一個字串中,也就是說在記憶體中是該數值每個數字的ASCII碼,而不是該數值的二進位表示。

    將數值拷貝到字串中,該字串是不定長的,會隨之數字個數的增加而增加。

    回覆
    0
  • 取消回覆