如何在C语言中连接两个数组?

13

在C语言中,如何将数组X和Y的元素包含到数组total中?能否给出一个例子?

X = (float*) malloc(4);
Y = (float*) malloc(4);
total = (float*) malloc(8);

for (i = 0; i < 4; i++)
{
    h_x[i] = 1;
    h_y[i] = 2;
}

//How can I make 'total' have both the arrays x and y
//for example I would like the following to print out 
// 1, 1, 1, 1, 2, 2, 2, 2

for (i = 0; i < 8; i++)
    printf("%.1f, ", total[i]);

4
什么问题?你尝试了什么?根据我所看到的,你知道如何遍历数组。 - Kiril Kirov
你的第一个问题是你为 X/Ytotal 分别分配了四个和八个 _字节_。 - Some programmer dude
1
C语言中两个数组的连接已经有答案了。https://dev59.com/70rSa4cB1Zd3GeqPUTJ0 - tiguero
8个回答

57

因为现有的代码根本没有考虑 sizeof(float),所以分配的内存量是错误的。

除此之外,你可以使用 memcpy 将一个数组附加到另一个数组上:

float x[4] = { 1, 1, 1, 1 };
float y[4] = { 2, 2, 2, 2 };

float* total = malloc(8 * sizeof(float)); // array to hold the result

memcpy(total,     x, 4 * sizeof(float)); // copy 4 floats from x to total[0]...total[3]
memcpy(total + 4, y, 4 * sizeof(float)); // copy 4 floats from y to total[4]...total[7]

1
非常感谢您给我提供了一个例子,这对我非常有帮助。 - Justin k
4
不应该对malloc的返回值进行强制类型转换(cast)。 - Eregrith
1
最好不要在sizeof中提及类型: float* total = malloc(8 * sizeof(*total)); - Déjà vu
在最后一个memcpy之后,total被视为更大的数组还是一个2x4矩阵? - elmazzun
@elmazzun 不确定你所说的“更大的数组”是什么意思?无论如何,total不是一个数组,因为它没有使用数组语法创建。这个差别可能看起来很小,但它确实存在。 - Jon
显示剩余2条评论

3
for (i = 0; i < 4; i++)
{
    total[i]  =h_x[i] = 1;
    total[i+4]=h_y[i] = 2;
}

1
仅适用于问题中的特定示例,而不适用于一般情况。 - stakx - no longer contributing
@stakx:我认为大多数好处不能使一个通用函数,我认为在这种情况下问题是需要该函数而不是通用函数。 - BLUEPIXY
@BLUEPIXY - 显然,两个输入数组具有相同数量的元素太特殊了。但是你的解决方案特别利用了这一点。 - user5683823

2
当您知道两个C数组的大小时,一种将它们连接起来的方法。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define ARRAY_CONCAT(TYPE, A, An, B, Bn) \
(TYPE *)array_concat((const void *)(A), (An), (const void *)(B), (Bn), sizeof(TYPE));

void *array_concat(const void *a, size_t an,
               const void *b, size_t bn, size_t s)
{
    char *p = malloc(s * (an + bn));
    memcpy(p, a, an*s);
    memcpy(p + an*s, b, bn*s);
    return p;
}

// testing
const int a[] = { 1, 1, 1, 1 };
const int b[] = { 2, 2, 2, 2 };

int main(void)
{
    unsigned int i;

    int *total = ARRAY_CONCAT(int, a, 4, b, 4);

    for(i = 0; i < 8; i++)
        printf("%d\n", total[i]);

    free(total);
    return EXIT_SUCCCESS;
}

2
太棒了!从http://www.rosettacode.org/wiki/Array_concatenation#C抄袭,获得三个赞!不过我会给你一个踩。 - user5683823

0

也许这很简单。

#include <stdio.h>

int main()
{
    int i,j,k,n,m,total,a[30],b[30],c[60];
    //getting array a
    printf("enter size of array A:");
    scanf("%d",&n);
    printf("enter %d elements \n",n);
    for(i=0;i<n;++i)
    {scanf("%d",&a[i]);}

    //getting aaray b
    printf("enter size of array b:");
    scanf("%d",&m);
    printf("enter %d elements \n",m);
    for(j=0;j<m;++j)
    {scanf("%d",&b[j]);}

    total=m+n;
    i=0,j=0;

    //concating starts    
    for(i=0;i<n;++i)
    {
       c[i]=a[i];
    }
    for(j=0;j<m;++j,++n)
    {
       c[n]=b[j];
    }

    printf("printing c\n");
    for(k=0;k<total;++k)
    {printf("%d\n",c[k]);}
}

0

我认为应该添加这个,因为过去我发现需要将值附加到 C 数组(例如 Objective-C 中的 NSMutableArray)。 这段代码管理一个 C 的 float 数组并将值附加到其中:

static float *arr;
static int length;

void appendFloat(float);

int main(int argc, const char * argv[]) {

    float val = 0.1f;
    appendFloat(val);

    return 0;
}

void appendFloat(float val) {
    /*
     * How to manage a mutable C float array
     */
    // Create temp array
    float *temp = malloc(sizeof(float) * length + 1);
    if (length > 0 && arr != NULL) {
        // Copy value of arr into temp if arr has values
        memccpy(temp, arr, length, sizeof(float));
        // Free origional arr
        free(arr);
    }
    // Length += 1
    length++;
    // Append the value
    temp[length] = val;
    // Set value of temp to arr
    arr = temp;
}

0

我喜欢Jon的答案。在我的情况下,我不得不使用静态解决方案。 因此,如果你被迫不使用动态内存分配:

int arr1[5] = {11,2,33,45,5};
int arr2[3] = {16,73,80};
int final_arr[8];

memcpy(final_arr, arr1, 5 * sizeof(int));
memcpy(&final_arr[5], arr2, 3 * sizeof(int));

for(int i=0; i<(sizeof(final_arr)/sizeof(final_arr[0]));i++){
    printf("final_arr: %i\n", final_arr[i]);
}

0
这里提供一种解决方案,用于连接两个或多个静态分配的数组。静态分配的数组是在编译时定义长度的数组。sizeof运算符返回这些数组的大小(以字节为单位):
char Static[16];               // A statically allocated array
int n = sizeof(Static_array);  // n1 == 16

我们可以使用运算符sizeof来构建一组宏,这些宏将连接两个或多个数组,并可能返回总数组长度。
我们的宏:
#include <string.h>

#define cat(z, a)          *((uint8_t *)memcpy(&(z), &(a), sizeof(a)) + sizeof(a))
#define cat1(z, a)         cat((z),(a))
#define cat2(z, a, b)      cat1(cat((z),(a)),b)
#define cat3(z, a, b...)   cat2(cat((z),(a)),b)
#define cat4(z, a, b...)   cat3(cat((z),(a)),b)
#define cat5(z, a, b...)   cat4(cat((z),(a)),b)
// ... add more as necessary
#define catn(n, z, a ...)  (&cat ## n((z), a) - (uint8_t *)&(z)) // Returns total length

使用示例:

char      One[1]   = { 0x11 };
char      Two[2]   = { 0x22, 0x22 };
char      Three[3] = { 0x33, 0x33, 0x33 };
char      Four[4]  = { 0x44, 0x44, 0x44, 0x44 };
char      All[10];
unsigned  nAll = catn(4, All, One, Two, Three, Four);

然而,由于我们定义宏的方式,只要sizeof返回它们的大小,我们就可以连接任何类型的对象。例如:

char      One      = 0x11;                                // A byte
char      Two[2]   = { 0x22, 0x22 };                      // An array of two byte
char      Three[]  = "33";                                // A string ! 3rd byte = '\x00'
struct {
    char  a[2];
    short  b;
}         Four     = { .a = { 0x44, 0x44}, .b = 0x4444 }; // A structure
void *    Eight    = &One;                                // A 64-bit pointer
char      All[18];
unsigned  nAll     = catn(5, All, One, Two, Three, Four, Eight);

使用常量字面值,我们可以使用这些宏来连接常量、函数结果甚至是常量数组:

// Here we concatenate a constant, a function result, and a constant array
cat2(All,(char){0x11},(unsigned){some_fct()},((uint8_t[4]){1,2,3,4}));

0
为什么不使用这样简单的逻辑呢?

enter image description here

#include<stdio.h>  
  
#define N 5  
#define M (N * 2)  
  
int main()  
{  
    int a[N], b[N], c[M], i, index = 0;  
  
    printf("Enter %d integer numbers, for first array\n", N);  
    for(i = 0; i < N; i++)  
        scanf("%d", &a[i]);  
  
    printf("Enter %d integer numbers, for second array\n", N);  
    for(i = 0; i < N; i++)  
            scanf("%d", &b[i]);  
  
    printf("\nMerging a[%d] and b[%d] to form c[%d] ..\n", N, N, M);  
    for(i = 0; i < N; i++)  
        c[index++] = a[i];  
  
    for(i = 0; i < N; i++)  
        c[index++] = b[i];  
  
    printf("\nElements of c[%d] is ..\n", M);  
    for(i = 0; i < M; i++)  
        printf("%d\n", c[i]);  
  
    return 0;  
} 

结果数组的大小必须等于数组a和b的大小。

来源:C语言程序连接两个数组


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接