1

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.

9
  • 6
    char(*t2)[10]; is a pointer to array of ten chars. So it's size is a size of a pointer. Commented Jun 3, 2022 at 14:55
  • 2
    OTOH, char *t1[10]; is an array of pointers. Not chars. So it is ten times as a size of a pointer. Commented Jun 3, 2022 at 14:57
  • I see, so the t1 have ten pointers and t2 is only a pointer to a ten char array. Why adding the "( )" on *t2 have this effect? Commented Jun 3, 2022 at 15:02
  • Because this is the syntax, as defined in the C language. Commented Jun 3, 2022 at 15:03
  • 1
    @Samuel One way to understand this is the "definition looks like use" rule. char *t1[10] means an item in t1 can be accessed with for example *t1[5] (which does [] first and then * so it must be an array of pointers). char (*t2)[10] means an item in t2 can be accessed with for example (*t2)[5] (which does * first and then [] so it must be a pointer to an array) Commented Jun 3, 2022 at 15:13

1 Answer 1

3

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];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.