What is being displayed when I read a two-dimensional array as a one-dimensional array?

arrays, c, multidimensional-array

Solution

What is being printed in the second for loop?

Short answer is "it's garbage". The official name for it is "undefined behavior", but it's a essentially you see a sequence of arbitrary decimal digits.

Long answer is a little trickier: you are passing `printf` addresses of one-dimension arrays, which get re-interpreted as integer numbers. Note how the numbers are apart by the same step of 16. This is the size of four `int`s on your system.

If you want to get the original numbers through an array of one dimension, you could force a different re-interpretation of the array - as a pointer to `int`:

int *ptr = (int*)&array;
for(i = 0; i < 16; i++){
    printf("%d ", ptr[i]);
}

This produces the sequence of numbers from your 2D array, the way the array is stored in memory (row-by-row).

Demo on ideone.

Problem

I am trying to understand the way that C handles arrays, in this case, by reading a two-dimensional array as though it were a one-dimensional array. Given this simple C program ``` #include <stdio.h> int main(int argc, char *argv[]){ int array[4][4]; int i, j; for(i = 0; i < 4; i++){ for(j = 0; j < 4; j++){ array[i][j] = (i+1)*(j+1); printf("%d ", array[i][j]); } printf("\n"); } for(i = 0; i < 16; i++){ printf("%d ", array[i]); } printf("\n"); } ``` I get this strange output. ``` 1 2 3 4 2 4 6 8 3 6 9 12 4 8 12 16 56319776 56319792 56319808 56319824 56319840 56319856 56319872 56319888 56319904 56319920 56319936 56319952 56319968 56319984 56320000 56320016 ``` What is being printed in the second `for` loop?

Original source