简体   繁体   English

C 中 _int8 数据类型的格式说明符

[英]Format specifier of _int8 data type in C

What is the format specifier for an _int8 data type? _int8 数据类型的格式说明符是什么?

I am using "%hd" but it is giving me an error about stack corruption.我正在使用“%hd”,但它给我一个关于堆栈损坏的错误。 Thanks :)谢谢 :)

This is a snippet of the code:这是代码片段:

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 "... but the next pointer is a pointer to a signed char or unsigned char". man scanf: %hhd "...但下一个指针是指向有符号字符或无符号字符的指针"。 An _int8 is equivalent to a signed char in any system you're going to be doing scanf on. _int8相当于您将在其上执行scanf任何系统中的带signed char

signed _int8 answer;
scanf("%hhd", &answer);
printf("You entered %d\n\n", answer);

To use the "explicit width" typedefs like int8_t and uint_fast16_t portably in C99 in the format strings of printf and scanf , you need to #include <inttypes.h> and then use the string macros PRIi8 and PRIuFAST16 , like so:要在 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);

See the manual for a full list, and cross-reference it with the typedefs in <stdint.h> .请参阅手册以获取完整列表,并将其与<stdint.h>的 typedef 交叉引用。

%hd will allow you to get a "short int", which is typically 16 bits, not 8 bits as might imagine. %hd 将允许您获得一个“短整数”,通常是 16 位,而不是想象中的 8 位。 If %hhd is not supported, you may not have a good way to do this, other than scanning in as a short and assigning.如果 %hhd 不受支持,除了作为短扫描和分配之外,您可能没有一个好的方法来做到这一点。

scanf with %hd reads a short int , which might be 16 bit on a 32 bit machine.带有%hd scanf读取一个short int ,它在 32 位机器上可能是 16 位。 So you are reading into answer and one byte beyond, thus the stack corruption.因此,您正在阅读答案并超出一个字节,因此堆栈损坏。

Up to C90 there is no type specifier to read an 8 bit int with scanf.在 C90 之前,没有类型说明符可以使用 scanf 读取 8 位 int。

%hhd is only available since C99, see also ANSI C (ISO C90): Can scanf read/accept an unsigned char? %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