c - 用 0 填充 C 数组

标签 c arrays addition

Array addition in C

这段代码有问题,我试图将 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/

相关文章:

c - 添加到 Linux 的系统调用的历史?

c - 使用 16b 值时检测溢出和进位

c - 如何通过 gcc 临时文件创建进行故障排除

检查函数中的指针地址和值

c - 在 C 中实现队列

java - 如何找到与特定值最接近的数组元素之和?

arrays - 将带有空格的字符串存储到 Arrays Bash 中

c++ - 将位集数组转换为整数数组

C++ 重载 : operator+ for adding Matrices by element

Java排序双向链表添加方法