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

I am trying to understand how C handles arrays, in this case, reading a two-dimensional array, as if 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 conclusion.

 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 printed in the second for loop?

+6
source share
2 answers

What is printed in the second cycle?

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

The long answer is a bit more complicated: you pass printf addresses of one-dimensional arrays that are interpreted as integers. Notice how the numbers are divided into the same step 16. This is the size of four int on your system.

If you want to get the source numbers through an array of one dimension, you can force another interpretation of the array as a pointer to int :

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

This creates a sequence of numbers from your 2D array, a way to store the array in memory (line by line).

Demo on ideon.

+4
source

2D arrays are considered a 1D array of 1D arrays. It prints the address of 1D arrays, but you must use the %p specifier to print the address, otherwise it causes 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 int arrays.

It should be noted that only your program causes undefined behavior for two reasons:
1. invalid pointer %d used to print the address.
2. You get access to the last cycle. for(i = 0; i < 16; i++) must be for(i = 0; i < 4; i++)

+4
source

Source: https://habr.com/ru/post/969994/


All Articles