convert array to two dimensional array by pointer

后端 未结 5 862
无人及你
无人及你 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?

    0 讨论(0)
  • 2020-12-17 02:31

    Yes, if you can use an array of pointers:

     int foo[] = {1,2,3,4,5,6};
     int *bla[2]={foo, foo+3};
    
    0 讨论(0)
  • 2020-12-17 02:46
    int (*blah)[3] = (int (*)[3]) foo; // cast is required
    
    for (i = 0; i < 2; i++)
      for (j = 0; j < 3; j++)
        printf("blah[%d][%d] = %d\n", i, j, blah[i][j]);
    

    Note that this doesn't convert foo from a 1D to a 2D array; this just allows you to access the contents of foo as though it were a 2D array.

    So why does this work?

    First of all, remember that a subscript expression a[i] is interpreted as *(a + i); we find the address of the i'th element after a and dereference the result. So blah[i] is equivalent to *(blah + i); we find the address of the i'th 3-element array of int following blah and dereference the result, so the type of blah[i] is int [3].

    0 讨论(0)
  • 2020-12-17 02:48

    You can't initialise an int bla[2][3] with an int* (what foo becomes in that context).

    You can achieve that effect by declaring a pointer to arrays of int,

    int (*bla)[3] = (int (*)[3])&foo[0];
    

    but be sure that the dimensions actually match, or havoc will ensue.

    0 讨论(0)
  • 2020-12-17 02:49

    You could use union to alias one array into the other:

    #include <stdio.h>
    
    union
    {
      int foo[6];
      int bla[2][3];
    } u = { { 1, 2, 3, 4, 5, 6 } };
    
    int main(void)
    {
      int i, j;
    
      for (i = 0; i < 6; i++)
        printf("u.foo[%d]=%d ", i, u.foo[i]);
      printf("\n");
    
      for (j = 0; j < 2; j++)
      {
        for (i = 0; i < 3; i++)
          printf("u.bla[%d][%d]=%d ", j, i, u.bla[j][i]);
        printf("\n");
      }
    
      return 0;
    }
    

    Output (ideone):

    u.foo[0]=1 u.foo[1]=2 u.foo[2]=3 u.foo[3]=4 u.foo[4]=5 u.foo[5]=6 
    u.bla[0][0]=1 u.bla[0][1]=2 u.bla[0][2]=3 
    u.bla[1][0]=4 u.bla[1][1]=5 u.bla[1][2]=6 
    
    0 讨论(0)
提交回复
热议问题