Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append two arrays in C language?

Tags:

arrays

c

How can I include the elements of array X and Y in to array total in C language ? can you please show with an example.

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]);
like image 788
Justin k Avatar asked Aug 13 '12 10:08

Justin k


2 Answers

Your existing code is allocating the wrong amount of memory because it doesn't take sizeof(float) into account at all.

Other than that, you can append one array to the other with 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]
like image 136
Jon Avatar answered Oct 18 '22 04:10

Jon


for (i = 0; i < 4; i++)
{
    total[i]  =h_x[i] = 1;
    total[i+4]=h_y[i] = 2;
}
like image 25
BLUEPIXY Avatar answered Oct 18 '22 04:10

BLUEPIXY