Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer in 2D Array [duplicate]

As a beginner programmer I am dealing with some simple problems related to Pointers. In the following code I found the value of *a and a are same in hexadecimal. But I can't understand the reason.

#include <stdio.h>
#include <stdlib.h>

main(){
    int a[5][5];
    a[0][0] = 1;

    printf("*a=%p  a=%p \n", *a, a);

    return 0;
}

Here is the output:

*a=0x7ffddb8919f0  a=0x7ffddb8919f0
like image 895
biswas N Avatar asked Aug 11 '15 17:08

biswas N


2 Answers

An array and its first element have the same address.:)

For this declaration

int a[5][5];

expression a used in the printf call is implicitly converted to the pointer to its first element. Expression *a yields the first element of the array that is in turn a one-dimensional array that also is converted to a pointer to its first element.

Thus expressions a and *a have the same value as expression &a[0][0]

like image 163
Vlad from Moscow Avatar answered Sep 28 '22 04:09

Vlad from Moscow


In C and C++ languages values of array type T [N] are implicitly converted to values of pointer type T * in most contexts (with few exceptions). The resultant pointer points to the first element of the original array (index 0). This phenomenon is informally known as array type decay.

printf argument is one of those contexts when array type decay happens.

A 2D array of type int [5][5] is nothing else than an "1D array of 1D arrays", i.e. it is an array of 5 elements, with each element itself being an array of 5 ints.

The above array type decay rule naturally applies to this situation.

The expression a, which originally has array type int [5][5], decays to a pointer of type int (*)[5]. The pointer points to element a[0], which is the beginning of sub-array a[0] in memory. This is the first pointer you print.

The expression *a is a dereference operator applied to sub-expression a. Sub-expression a in this context behaves in exactly the same way as before: it decays to pointer of type int (*)[5] that points to a[0]. Thus the result of *a is a[0] itself. But a[0] is also an array. It is an array of int[5] type. It is also subject to array type decay. It decays to pointer of type int *, which points to the first element of a[0], i.e. to a[0][0]. This is the second pointer you print.

The reason both pointer values are the same numerically is that the beginning of sub-array a[0] corresponds to the same memory location as element a[0][0].

like image 35
AnT Avatar answered Sep 28 '22 04:09

AnT