我正在尝试使用 atoi
将 char 数组转换为整数。但是下面的代码会产生段错误。
代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
char a[10] = "1234567890";
int x,i;
for(i=0;i<strlen(a);i++){
x=atoi(a[i]);
printf("%d",x);
}
return 0;
}
我做错了什么,除了使用 atoi
之外,还有什么我可以使用的吗?
最佳答案
char a[10] = "1234567890";
这没有为空终止符留下空间。因此 strlen(a)
导致未定义的行为。像这样声明 a
:
const char a[] = "1234567890";
或者像这样:
const char *a = "1234567890";
随后,您对 atoi
的调用不正确。您打算将指针传递给空终止字符串。您传递一个 char
。也许你的意思是传递 a+i
:
x=atoi(a+i);
话又说回来,循环的原因一点也不明显。有什么问题:
x = atoi(a);
此外,atoi
是一个众所周知的难用函数。它不会为您提供任何有意义的方法来检测输入中的错误。更好的方法是使用 sscanf
。
你可以像这样把它们放在一起:
#include<stdio.h>
int main(void)
{
const char *a = "1234567890";
for(size_t i = 0; a[i]; i++)
{
int x;
if (sscanf(a + i, "%d", &x) == 1)
{
printf("%d\n", x);
}
}
return 0;
}
它的输出是:
1234567890 234567890 34567890 4567890 567890 67890 7890 890 90 0
But I doubt that's what you want. I suspect that you really want this:
#include<stdio.h>
int main(void)
{
int x;
if (sscanf("1234567890", "%d", &x) == 1)
{
printf("%d\n", x);
}
return 0;
}
输出是:
1234567890
关于使用atoi将char数组转换为整数导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26489451/