[英]Format specifier of _int8 data type in C
_int8 數據類型的格式說明符是什么?
我正在使用“%hd”,但它給我一個關於堆棧損壞的錯誤。 謝謝 :)
這是代碼片段:
signed _int8 answer;
printf("----Technology Quiz----\n\n");
printf("The IPad came out in which year?\n");
printf("Year: ");
scanf("%hd", &answer);
printf("\n\n");
printf("The answer you provided was: %hd\n\n", answer);
man scanf: %hhd
"...但下一個指針是指向有符號字符或無符號字符的指針"。 _int8
相當於您將在其上執行scanf
任何系統中的帶signed char
。
signed _int8 answer;
scanf("%hhd", &answer);
printf("You entered %d\n\n", answer);
要在 C99 中以printf
和scanf
的格式字符串可移植地使用“顯式寬度”類型定義,例如int8_t
和uint_fast16_t
,您需要#include <inttypes.h>
然后使用字符串宏PRIi8
和PRIuFAST16
,如下所示:
#include <stdint.h> // for the typedefs (redundant, actually)
#include <inttypes.h> // for the macros
int8_t a = 1;
uint_fast16_t b = 2;
printf("A = %" PRIi8 ", B = %" PRIuFAST16 "\n", a, b);
請參閱手冊以獲取完整列表,並將其與<stdint.h>
的 typedef 交叉引用。
%hd 將允許您獲得一個“短整數”,通常是 16 位,而不是想象中的 8 位。 如果 %hhd 不受支持,除了作為短掃描和分配之外,您可能沒有一個好的方法來做到這一點。
帶有%hd
scanf
讀取一個short int
,它在 32 位機器上可能是 16 位。 因此,您正在閱讀答案並超出一個字節,因此堆棧損壞。
在 C90 之前,沒有類型說明符可以使用 scanf 讀取 8 位 int。
%hhd
僅在 C99 后可用,另見ANSI C (ISO C90): Can scanf read/accept an unsigned char? .
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.