【发布时间】:2016-03-27 13:27:19
【问题描述】:
我的程序的这一部分旨在遍历字符串的chars,并选择字符串中的所有数字并将它们放入一个名为helper 的数组中。这是我正在处理的一个较大程序的一小部分,我已尽力只提供有用的代码段。我也知道没有正确使用指针会导致分段错误,但是我的问题是我找不到错误使用指针的位置。
所以,当我尝试编译以下代码时,我遇到了一个分段错误(核心转储)...
#include <stdio.h>
#include <string.h>
int main(void)
{
char *eq = "y=344+99";
int helper[50];
unsigned short int helperWriter = 0, i;
for (i = 0; i < eq[i]; i++) //
{
if (isdigit(eq[i]))
{
unsigned short int d;
for (d = i; eq[d]; d++)
{
if (isdigit(eq[d]))
{
int temp = atoi(eq[d]);
helper[helperWriter] = temp;
printf("%d", helperWriter);
}
helperWriter++;
}
}
}
}
我对 C 很陌生,反过来,我对指针也很陌生,所以我的错误可能很愚蠢。如果需要任何额外信息,请询问。
【问题讨论】:
-
试试
for (d = i; equation.eq[d]; d++),不然会死循环,最后越界 -
你做这个作业时
helpWriter有多大? -
在使用它之前测试索引,并在消息末尾添加
newline。if(helpwriter >= 50) { printf("index o/range\n"); } -
这是有错误的行:
int temp = atoi(eq[d]);它会导致段错误,因为您忽略了警告。
标签: c arrays string pointers segmentation-fault