这段代码有问题,我试图将 array1 与 array2 相加。
我通过命令行参数输入 array2 的数字。
当我输入 10 个数字时,它可以正常工作,但是当我添加的数字少于 10 个时,我会收到内存访问错误。
我现在的问题是:如何用数字 0 填充缺失的数组字段?例如:我输入 9 个数字,第 10 个字段应为 0。
最佳答案
您没有检查传递了多少个命令行参数,当您索引命令行参数数组时,您将收到越界错误。
在 addiren
函数中,您应该利用传递的 argc
并在 for 循环限制中使用它。
#include <stdio.h>
#include <stdlib.h>
int addiren(int argc, char**argv){
int array_one[10] = {0,1,1,2,3,5,8,13,21,35};
int array_two[10] = {0}; //Quick way to set the array to all zeros
int array_three[10] = {0};
//Set array_two with your cmd-line args, notice the use of argc
for(int i = 1; i<argc && i<=10; i++){
array_two[i-1] = atoi(argv[i]);
}
//Add array_one with array_two to array_three
for(int i = 0; i<10; i++){
array_three[i] = array_one[i]+array_two[i];
}
//Return an int since that's what the function return type requires
return 0;
}
希望这有帮助!
关于c - 用 0 填充 C 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42845837/