[C++] 用 printf() 印出 size_t 型態的變數

[C++] 用 printf() 印出 size_t 型態的變數

今天想要在 C++ 程式裡用 printf() 印一個 size_t 的變數值,

結果 gcc 出現了編譯警告:

Test.cpp:113:76: warning: format '%d' expects argument of type 'int', but argument 2 has type 'size_t {aka long unsigned int}' [-Wformat=]
printf("Thread %d is running\n", iThread);

 

嗯… 想想 size_t 是 unsigned 類型的,把 %d 改成 %u 好了,結果還是不行:

Test.cpp:113:76: warning: format '%u' expects argument of type 'unsigned int', but argument 2 has type 'size_t {aka long unsigned int}' [-Wformat=]
printf("Thread %u is running\n", iThread);

 

查了一下,原來要用 %zu 這個方式,跟 printf() 指明這個變數是 size_t 的長度才行:

printf("Thread %zu is running\n", iThread);

 

參考資料:stackoverflow: How can one print a size_t variable portably using the printf family?

 

(本頁面已被瀏覽過 5,720 次)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料