convert array to two dimensional array by pointer

后端 未结 5 880
无人及你
无人及你 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: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].

提交回复
热议问题