简体   繁体   English

如何将 C 中的两个整数数组与 for 循环合并

[英]How can I merge two integer arrays in C with for loops

I am trying to merge two arrays but there seems to be a problem.我正在尝试合并两个数组,但似乎有问题。 I try to use a simple loop but it doesn't work.我尝试使用一个简单的循环,但它不起作用。 My first problem is that I don't know how to stop the for loop for an array, and the second is that every time it assigns some garbage value to the merged array.我的第一个问题是我不知道如何停止数组的 for 循环,第二个问题是每次它为合并的数组分配一些垃圾值时。 If someone could just give me a direction…如果有人能给我一个方向……

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]);
}

As C is a procedural language, it is good to define functions for such operations.由于 C 是一种过程语言,因此最好为此类操作定义函数。 C standard provides a special type size_t for the sizes. 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;
}

or more generic one:或更通用的一个:

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;
}

where all sizes are in the elements.所有尺寸都在元素中。 elemSize in bytes. elemSize 以字节为单位。

You can pass your own buffer (destination array) or NULL - then the function will allocate it for you.您可以传递您自己的缓冲区(目标数组)或 NULL - 然后该函数将为您分配它。 If the maxSize is zero it allocates as much memory as needed to accommodate both arrays.如果 maxSize 为零,它会根据需要分配尽可能多的内存来容纳两个数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM