How are 3D arrays stored in C?

前端 未结 8 2319
半阙折子戏
半阙折子戏 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

    Yep, you're right - they are stored consecutively. Consider this example:

    #include 
    
    int array3d[2][3][2] = {
      {{0, 1}, {2, 3}, {3, 4}},
      {{5, 6}, {7, 8}, {9, 10}}
    };
    
    int main()
    {
      int i;
      for(i = 0; i < 12; i++) {
        printf("%d ", *((int*)array3d + i));
      }
      printf("\n");
      return 0;
    }
    

    Output:

    0 1 2 3 3 4 5 6 7 8 9 10

提交回复
热议问题