convert array to two dimensional array by pointer

后端 未结 5 881
无人及你
无人及你 2020-12-17 02:22

Is it possible to convert a single dimensional array into a two dimensional array?

i first tought that will be very easy, just set the pointer of the 2D array to the

5条回答
  •  暖寄归人
    2020-12-17 02:28

    I know you specificed pointers... but it looks like you're just trying to have the data from an array stored in a 2D array. So how about just memcpy() the contents from the 1 dimensional array to the two dimensional array?

    int i, j;
    int foo[] = {1, 2, 3, 4, 5, 6};
    int bla[2][3];
    memcpy(bla, foo, 6 * sizeof(int));
    for(i=0; i<2; i++)
       for(j=0; j<3; j++)
          printf("bla[%d][%d] = %d\n",i,j,bla[i][j]);
    

    yields:

    bla[0][0] = 1
    bla[0][1] = 2
    bla[0][2] = 3
    bla[1][0] = 4
    bla[1][1] = 5
    bla[1][2] = 6
    

    That's all your going for, right?

提交回复
热议问题