c++ - sprintf_s第二个参数的设置问题?
巴扎黑
巴扎黑 2017-04-17 15:16:43
0
3
638
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 的异常
请问这个情况怎么解释?

巴扎黑
巴扎黑

全部回覆(3)
Peter_Zhu

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

Peter_Zhu

注意一下第三行到第五行

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。

PHPzhong

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

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

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!