首页 > 解决方案 > 在c中减去不同大小的数组

问题描述

void function(int first[], int second[], int third[]) {
       int i;
       for(i=0;i<64;i++) {
          third[i] = first[i] - second[i];
       }
    }

我想从第一个数组中减去第二个数组。第一个包含 32 个数字,第二个包含 13 个数字。它适用于前 13 个数字。一旦第二个数组“用完”元素,我想使用第二个数组开头的数字。所以我想从第一个数组的第 14 个元素中减去第二个数组的第一个元素,依此类推……我怎样才能实现呢?

标签: carrays

解决方案


您可以使用%从数组的长度获取索引的剩余部分,这样,您可以循环遍历第二个数组!我按照您的要求更改了您的代码

// get the length of array before you pass it to the function like this:
// int second_len = sizeof(second) / sizeof(second[0]);
void function(int first[], int second[], int third[], int second_len) {
    int i;
    for(i=0;i<64;i++) {
        third[i] = first[i] - second[i % second_len];
    }
}

推荐阅读