簡體   English   中英

C 中 _int8 數據類型的格式說明符

[英]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 中以printfscanf的格式字符串可移植地使用“顯式寬度”類型定義,例如int8_tuint_fast16_t ,您需要#include <inttypes.h>然后使用字符串宏PRIi8PRIuFAST16 ,如下所示:

#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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM