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]);
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]
for (i = 0; i < 4; i++)
{
total[i] =h_x[i] = 1;
total[i+4]=h_y[i] = 2;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With