如何使用for循环合并C中的两个整数数组

时间:2019-06-29 15:41:28

标签: c arrays for-loop

我正在尝试合并两个数组,但是似乎有问题。我尝试使用一个简单的循环,但它不起作用。我的第一个问题是我不知道如何停止数组的for循环,第二个问题是每次它为合并的数组分配一些垃圾值。如果有人可以给我指示...

int arr1[] = {1,2,3,4,5,0}, arr2[] = {6,7,8,9,0};

int x = 0, merge_arr[x], i = 0, x1 = 0;

for( ; arr1[i] != 0; i++)
{
    merge_arr[i] = arr1[i];
    printf("%di ", merge_arr[i]);
}

for( ; arr2[x1] != 0; i++)
{
    merge_arr[i] = arr2[x1];
    printf(" %di ", merge_arr[i]);
    x1++;
}

for(int x2 = 0; merge_arr[x2] != '\0'; x2++)
{
    printf("%d\n", merge_arr[x2]);
}

1 个答案:

答案 0 :(得分:1)

由于C是一种程序语言,因此最好为此类操作定义函数。 C标准为尺寸提供了特殊的类型size_t

int *concatIntArrays(int *dest, size_t maxSize, const int *arr1, const size_t arr1Size, const int *arr2, const size_t arr2Size)
{
    size_t toCopy;
    if(!dest)
    {
        dest = malloc(maxSize ? maxSize * sizeof(*dest) : (maxSize = (arr1Size + arr2Size)) * sizeof(*dest));
    }
    if(dest)
    {
        if(arr1Size <= maxSize) toCopy = arr1Size;
        else toCopy = maxSize;
        memcpy(dest, arr1, toCopy * sizeof(*dest));

        maxSize -= toCopy;

        if(arr2Size <= maxSize) toCopy = arr2Size;
        else toCopy = maxSize;
        memcpy(dest + arr1Size, arr2, toCopy * sizeof(*dest));
    }
    return dest;
}

或更通用的一个:

void *concatArrays(void *dest, const size_t elemSize, size_t maxSize, const void *arr1, const size_t arr1Size, const void *arr2, const size_t arr2Size)
{
    size_t toCopy;
    char *tempdest = dest;
    if(!dest)
    {
        dest = malloc(maxSize ? maxSize * elemSize : (maxSize = (arr1Size + arr2Size)) * elemSize);
    }
    if(dest)
    {
        if(arr1Size <= maxSize) toCopy = arr1Size;
        else toCopy = maxSize;
        memcpy(dest, arr1, toCopy * elemSize);

        maxSize -= toCopy;

        if(arr2Size <= maxSize) toCopy = arr2Size;
        else toCopy = maxSize;
        memcpy(tempdest + arr1Size * elemSize, arr2, toCopy * elemsize);
    }
    return dest;
}

所有尺寸均在元素中。 elemSize(以字节为单位)。

您可以传递自己的缓冲区(目标数组)或NULL-然后函数将为您分配它。如果maxSize为零,则它将分配所需的内存以容纳两个阵列。