Search code examples
arrayscloops2dtransfer

How can I transfer 2D array to 1D array without using Loop in C?


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...


Solution

  • 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];