Tanvi Tanvi - 3 months ago 10
C Question

Why *pointer_name behaves differently in 1D and 2D array

Why is it that when

*q
is used in 1D array it gives the value in the array whereas
*p
in 2D array gives an address instead. Isn't
*pointer_name
supposed to tell what is stored, so why is output an address instead of
40
(the value in array)?

#include<stdio.h>
int main(){
int a[3][4] = {
{40, 1, 2, 3} ,
{4, 5, 6, 7} ,
{8, 9, 10, 11}
};
int (*p)[4] = a;

int b[4] = {3,4,8,5};
int *q = b;

printf("%d, %d",*q, *p);// output- 3, 10485040

return 0;
}

Answer

Because p is a pointer to an array. When you dereference p the array will decay to a pointer to the first element. Doing *p and &(*p)[0] is equivalent (and also equivalent to &a[0][0]).

If you want to print the first element then you need to dereference both pointers, i.e. **p.

Comments