#include <stdlib.h>
#include <stdio.h>
main()
{
const char* str_int = "777";
const char* str_float = "333.3";
int i = atoi(str_int);
float f = atof(str_float);
printf("%s %s", i, f);
}
我已经尝试了几个我在网上找到的示例代码,它们都会导致总线错误。为什么会这样?
最佳答案
您的 printf
不正确。试试这个:
printf("%d %f", i, f);
问题是您的格式说明符是 %s
,它需要字符串。但是你给了它一个 int
和一个 float
。因此结果是未定义的行为。
它崩溃的原因是因为 printf
将尝试将参数作为字符串(指针)读取并照此引用它们,但它们是无效指针。
这是关于 printf
及其格式说明符的引用:
关于c - 为什么 atoi() 会导致总线错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8060861/