I have two arrays: one 2D, arr, the other 1D, ar, for example like this :
int arr[1][18]; int ar[18];
I want to copy arr[1][18] to ar[18] ""without using loop"". How can I do this?
I would appreciate if someone could explain this.
Thanks a lot in advance...
1 Answer
If you don't want to use a loop, you can use the function memcpy instead:
#include <stdio.h>
#include <string.h>
int main( void )
{
//declare and initialize the 2D array
int arr_2D[2][18] = {
{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 },
{ 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36 }
};
//declare the 1D array
int arr_1D[18];
//copy arr_2D[1] to arr_1D (without a loop)
memcpy( arr_1D, arr_2D[1], sizeof *arr_2D );
//print the result of the copy (in a loop)
for ( int i = 0; i < 18; i++ )
{
printf( "%d ", arr_1D[i] );
}
printf( "\n" );
}
This program has the following output:
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
As you can see, arr_2D[1] was successfully copied to arr_1D without a loop. A loop was only used for printing the result.
However, it is worth noting that memcpy is most likely using some kind of loop internally. Therefore, even if the code does not have a loop, you are still technically using a loop. There is no way to solve this problem without some kind loop, except by unrolling the loop, like this:
arr_1D[0] = arr_2D[1][0];
arr_1D[1] = arr_2D[1][1];
arr_1D[2] = arr_2D[1][2];
arr_1D[3] = arr_2D[1][3];
arr_1D[4] = arr_2D[1][4];
arr_1D[5] = arr_2D[1][5];
arr_1D[6] = arr_2D[1][6];
arr_1D[7] = arr_2D[1][7];
arr_1D[8] = arr_2D[1][8];
arr_1D[9] = arr_2D[1][9];
arr_1D[10] = arr_2D[1][10];
arr_1D[11] = arr_2D[1][11];
arr_1D[12] = arr_2D[1][12];
arr_1D[13] = arr_2D[1][13];
arr_1D[14] = arr_2D[1][14];
arr_1D[15] = arr_2D[1][15];
arr_1D[16] = arr_2D[1][16];
arr_1D[17] = arr_2D[1][17];
2 Comments
Blindy
What do you believe
memcpy does?Andreas Wenzel
@Blindy: Yes, you are correct that
memcpy most likely also uses a loop internally. I have edited my answer to mention this.
memcpy. Of course it uses a loop internally for that large a copy.arr[0]toar(as both are 18 element arrays ofint).int arr[1][18];declares a 2D array in which the outer array only has a single element. Is that really what you want? See my answer for an example of a 2D array which has several elements in the outer array.int ar[18];toint *ar;. Then you can just sayar = arr[0];. (But in this case you're not making a copy.)