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?
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.
2D arrays are thought as 1D array of 1D arrays. It is printing the address of 1D arrays but you should use %p
specifier to print the address otherwise it invokes undefined behavior.
for(i = 0; i < 4; i++){
printf("%p", (void *)array[i]);
}
int array[4][4]
is of type 2D array of 16 integers or you can say that array
is a 1D array of 4 1D arrays of int
's.
You should note that only your program invokes undefined behavior for two reasons:
1. wrong specifier %d
is used to print address.
2. you are accessing out of bound in your last loop. for(i = 0; i < 16; i++)
should be for(i = 0; i < 4; i++)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With