我正在尝试将放在命令行上的参数放入一个整数数组中,这样我就可以对它们进行计算。为了解决这个问题,我正在做的是从 argv[1](我不需要 ./a.out)开始获取参数并将它们放入一个字符数组中,然后我检查它是否是一个数字。如果是这样,我将它们放入一个整数数组中。我现在的问题是我遇到了总线错误。我的代码如下。非常感谢您提供的任何建议。谢谢。
这是我的输入:
./a.out 2 3
和我的输出:
Good
Input 1 is good
Bus error: 10
代码: *
int main (int argc, char *argv[ ] )
{
.... //declaration of variables
if (argc == 3) {
printf("Good\n");
}
else {
printf("Wrong amount of inputs\n");
exit(0);
}
for (i = 1; i < argc; i++) {
//length = strlen(argv[i]);
//theinputs[i] = malloc((length + 1) * (sizeof(char)));
strcpy(theinputs[i - 1], argv[i]);
if ( isdigit(*theinputs[i-1]) ) {
printf("Input %d is good\n", i);
}
else {
printf("One or more of your inputs is not an integer %s.\n", theinputs[i]);
//return -1; //Inputs are not being read correctly
exit(0);
}
numbers[i] = atoi(theinputs[i]);
}
for (i = 0; i < 2; i++) {
printf("%d\n", numbers[i]);
}