Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behavior of 2D arrays

I have created a 2D array, and tried to print certain values as shown below:

int a[2][2] = { {1, 2}, 
                {3, 4}};

printf("%d %d\n", *(a+1)[0], ((int *)a+1)[0]);

The output is:

3 2

I understand why 3 is the first output (a+1 points to the second row, and we print its 0th element.

My question is regarding the second output, i.e., 2. My guess is that due to typecasting a as int *, the 2D array is treated like a 1D array, and thus a+1 acts as pointer to the 2nd element, and so we get the output as 2.

Are my assumptions correct or is there some other logic behind this?
Also, originally what is the type of a when treated as pointer int (*)[2] or int **?

like image 505
Kevin Richards Avatar asked Jul 16 '14 22:07

Kevin Richards


People also ask

What are the characteristics of 2D arrays?

Two-dimensional (2D) arrays are indexed by two subscripts, one for the row and one for the column. Each element in the 2D array must by the same type, either a primitive type or object type.

Are 2D arrays contiguous in memory?

Yes they are contiguous.

How is 2D array represented?

The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices which can be represented as the collection of rows and columns. However, 2D arrays are created to implement a relational database lookalike data structure.

Are 2D arrays dynamic?

A 2D array can be dynamically allocated in C using a single pointer. This means that a memory block of size row*column*dataTypeSize is allocated using malloc and pointer arithmetic can be used to access the matrix elements.


1 Answers

When you wrote expression

(int *)a

then logically the original array can be considered as a one-dimensional array the following way

int a[4] = { 1, 2, 3, 4 };

So expression a points to the first element equal to 1 of this imaginary array. Expression ( a + 1 ) points to the second element of the imaginary array equal to 2 and expression ( a + 1 )[0] returns reference to this element that is you get 2.

like image 108
Vlad from Moscow Avatar answered Sep 28 '22 12:09

Vlad from Moscow