I'm learning pointers, and I'm kind of confused because of the output given by the following program:
#include <stdio.h>
#define R 10
#define C 20
int main()
{
int arr[R][C];
int (*p)[R][C]=&arr;
printf("%d ", sizeof(p));
printf("%d ", sizeof(*p));
return 0;
}
output : 4
800
why the output is 800
? we know that p
is a pointer that has a base type of a 2-D array of 10
rows and 20
columns, that means *p
points to the 0th array
of the matrice, which means sizeof(*p)=20*sizeof(int)=80
and sizeof(p)
should be equivalent to 800
but the output is way different from my calculations!
can I get an explanation ? much appreciated.
TL;DR - Always follow the data type!
p
is a pointer type variable, so sizeof(p)
is the size of a pointer on your platform, which happens to be 4
.
sizeof(*p)
, is the same as sizeof(int[R][C])
, which is the size of an int
, multiplied by R
and C
. The result is sizeof(int) == 4
(on your platform), 10
and 20
, multiplied together, 800
.
Note: In case of sizeof
operator, the array does not decay to a pointer to the first element, it retains the type.
That said, sizeof
yields a result of type size_t
, use %zu
format specifier to print the result.