Search code examples
carraysmultidimensional-arrayinitializationinitializer-list

Why does this program print 0 instead of the specific set of values from a specified array?


I'd like to know why the printf function in this tiny program returns 0 instead of the array of numbers 3 2 2:

int main(){
    int mat[2][2][2] = {{3,1,1},{2,2,2}};

    printf("first x, 2nd y, 2nd z = %d\n",mat[0][1][1]);
}

While working with X by Y matrices in C retrieving any value XxY was a breeze, but once I added another dimension I ran into this problem. I think I must've a misunderstanding of the way C deals with coordinates in arrays. Thanks a lot!


Solution

  • In

    int mat[2][2][2] = {{3,1,1},{2,2,2}};

    you declare a 3D array but you give initialization for a 2D, the values are not placed where you expect

    #include <stdio.h>
    
    int main(){
      int mat[2][2][2] = {{3,1,1},{2,2,2}};
    
      for (int i = 0; i != 2; ++i)
        for (int j = 0; j != 2; ++j)
          for (int k = 0; k != 2; ++k)
            printf("%d %d %d -> %d\n", i, j, k, mat[i][j][k]);
      return 0;
    }
    

    Execution : pi@raspberrypi:/tmp $ ./a.out

    0 0 0 -> 3
    0 0 1 -> 1
    0 1 0 -> 1
    0 1 1 -> 0
    1 0 0 -> 2
    1 0 1 -> 2
    1 1 0 -> 2
    1 1 1 -> 0
    pi@raspberrypi:/tmp $ 
    

    Furthermore because your array has 8 int but the init value has only 6 the compiler initializes the two not specified entries with 0