Home > database >  Question on "sizeof" char pointer array in C
Question on "sizeof" char pointer array in C

Time:06-04

I have two char arrays as below:

char *t1[10];
char(*t2)[10];

when using sizeof to find their size

printf("sizeof(t1): %d\n", sizeof(t1));
printf("sizeof(t2): %d\n", sizeof(t2));

I found that the output is:

sizeof(t1): 80
sizeof(t2): 8

I am quite confused by why I have two different results when using the sizeof operator.

CodePudding user response:

For starters you have to use the conversion specifier zu instead of d when outputting values of the type size_t

printf("sizeof(t1): %zu\n", sizeof(t1));
printf("sizeof(t2): %zu\n", sizeof(t2));

This record

char(*t2)[10];

does not declare an array. It is a declaration of a pointer to the array type char[10].

So sizeof( t1 ) yields the size of an array while sizeof( t2 ) yields the size of a pointer.

Consider for example declarations

char t1[5][10];
char ( *t2 )[10] = t1;

The pointer t2 is initialized by the address of the first element (of the type char[10]) of the array t1. That is it points to the first element of the array t1.

Also consider the following call of printf

printf("sizeof( *t2 ): %zu\n", sizeof( *t2 ));

The output of the call will be 10.

That is dereferencing the pointer you will get one dimensional array of the type char[10].

If you want to get identical outputs then the second declaration should be rewritten like

char *t1[10];
char *( t2)[10];
  • Related