0

In the below code if I change int (*p)[R][C]; to int p[R][C]; result change from 800 to 80. why does this happens as i understand in int p[R][C]; array name p is also a pointer like *p inint (*p)[R][C];

#include <stdio.h>

#define R 10
#define C 20

int main()
{
   int (*p)[R][C];
   printf("%d",  sizeof(*p));
   getchar();
   return 0;
}

PS:- is *p inint (*p)[R][C]; acting as a pointer to another pointer which is actually pointing to the array?

3
  • 1
    the first creates an array of pointers not an array of ints. Commented Feb 7, 2020 at 16:51
  • 2
    @johnelemans the first is a pointer to a multidimensional integer array not array of pointers! Commented Feb 7, 2020 at 16:54
  • printf("%d", sizeof(*p)); is wrong. sizeof() returns size_t, and the correct format specifier for size_t is %zu. Commented Feb 7, 2020 at 17:02

1 Answer 1

1

This

int (*p)[R][C];

declares a pointer to an array having the type int[R][C]. The result of the expression sizeof( int[R][C] ) is equal to R * C * sizeof( int ).

The expression *p has the type int[R][C]. So sizeof( *p ) is equivalent to sizeof( int[R][C] ).

As for this declaration

int p[R][C];

then the array designator p in the expression *p is converted to pointer to its first element and dereferencing the pointer you will get the first element of the array that has the type int[C].

So for the first declaration of the variable p as a pointer sizeof( *o ) is equal to sizeof( int[R][C].

For the second declaration of the variable p as a two-dimensional array sizeof( *p ) is equal to sizeof( int[C] ).

Using the first declaration of p as a pointer you could get the same result as for p declared as an array if you wrote

sizeof( **p )

That is dereferencing the pointer the first time you get an object of the type that is used in the second declaration to declare the variable p as an array.

Pay attention to that this call

printf("%d",  sizeof(*p));

has undefined behavior because there is used a wrong conversion format. You have to write

printf("%zu",  sizeof(*p));
Sign up to request clarification or add additional context in comments.

7 Comments

Does that means *p in int (*p)[R][C]; acting as a pointer to another pointer which is actually pointing to the array?
@gisire It is a pointer to an object of the array type int[R][C].
As I think *p in int (*p)[R][C]; is like we are dereferencing p one time so now we are actually at p[0] which is the first element in array p
@gisire This int (*p)[R][C]; is a declaration of a pointer. The record *p used in expressions yields the pointed object that is an object of the type int[R][C]. It is the same as if you have a declaration like int *p; then expression *p yields an object of the type int.
@Kaz No, the question is not about this. It is about the sizeof operator and the dereferencing operator.
|