如果num
的类型为int
,此程序将有效。但是,当将其更改为int8_t
时,num
后scanf()
将始终为0。
这是因为%d
中的scanf
吗?
#include <stdio.h>
#include <stdint.h>
void convert(int8_t, int8_t);
int main(int argc, char const *argv[]) {
int8_t num;
int8_t b;
printf("enter a number:\n");
while (1 == scanf("%d", &num)) {
scanf("%d", &b);
printf("%d %d\n", num, b);
printf("Code: ");
convert(num, b);
putchar('\n');
printf("enter a integer (q to quit):\n");
}
printf("done.\n");
getchar();
return 0;
}
void convert(int8_t n, int8_t base) {
if (n >= base)
convert(n / base, base);
printf("%d", n % base);
return;
}
答案 0 :(得分:5)
您将错误的参数传递给scanf
,%d
需要int
的地址。
您可以使用宏SCNd8
来获取int8_t
的输入。标题<intypes.h>
。
scanf("%"SCNd8, &b);
宏PRId8
打印其值。
答案 1 :(得分:1)
%d
的{{1}}格式说明符要求参数为scanf
的地址,在大多数系统上为4或8字节。您将int
的地址传递给它,该地址只有1个字节。因此int8_t
将结果值写入4-8个字节而不是1,从而导致未定义的行为。
您需要使用scanf
,它需要指向%hhd
(与char
相同)的指针作为其参数。