Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 854
Joshua Cook Avatar asked May 28 '14 18:05

Joshua Cook


2 Answers

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 ints 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.

like image 113
Sergey Kalinichenko Avatar answered Nov 15 '22 03:11

Sergey Kalinichenko


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++)

like image 39
haccks Avatar answered Nov 15 '22 04:11

haccks