How are 3D arrays stored in C?

前端 未结 8 2281
半阙折子戏
半阙折子戏 2020-11-29 23:17

I understand that arrays in C are allocated in row-major order. Therefore, for a 2 x 3 array:

0  1
2  3
4  5

Is stored in memory as

8条回答
  •  醉梦人生
    2020-11-29 23:45

    Yes, they're are just stored in consecutive order. You can test that like this:

    #include 
    
    int main (int argc, char const *argv[])
    {
      int numbers [2][3][4] = {{{1,2,3,4},{5,6,7,8},{9,10,11,12}}
                              ,{{13,14,15,16},{17,18,19,20},{21,22,23,24}}};
    
      int i,j,k;
    
      printf("3D:\n");
      for(i=0;i<2;++i)
        for(j=0;j<3;++j)
          for(k=0;k<4;++k)
            printf("%i ", numbers[i][j][k]);
    
      printf("\n\n1D:\n");
      for(i=0;i<24;++i)
        printf("%i ", *((int*)numbers+i));
    
      printf("\n");
    
      return 0;
    }
    

    That means that accesses to a multiindexed array with dimensions (N,M,L) are transformed to onedimensional accesses like this:

    array[i][j][k] = array[M*L*i + L*j + k]
    

提交回复
热议问题