c - 为什么 atoi() 会导致总线错误?

标签 c atoi

#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 及其格式说明符的引用:

http://www.cplusplus.com/reference/clibrary/cstdio/printf/

关于c - 为什么 atoi() 会导致总线错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8060861/

相关文章:

c - 这是 Tokyo Cabinet 的错误吗?

c - 提取特定范围的位并在 C 中找到它们之间的零数

c - C语言中匹配IP地址的最佳正则表达式或技术是什么

c - string.h 和 stdlib.h 函数给我错误 : undefined reference to '...'

c - 为什么我的小程序崩溃了?

c - 如何将解压结构的内容复制到 __packed__ 结构?

c - 帮助在 Visual Studio 2008 中打开文件

c++ - atoi 转换返回单个数字值

c++ - 从字符串中提取单个字符并将其转换为 int

ios - 奇怪的 atoi(char *) 问题