Yaron Scherf
Yaron Scherf

Reputation: 105

Pointers to array of pointers in c

Can someone please explain me what is the difference between the two following declarations:

char (*arr_a)[5];
char arr_b[20];

and why:

sizeof (*arr_b) = sizeof (char)
sizeof (*arr_a) = 5*sizeof(char)

Upvotes: 0

Views: 73

Answers (2)

haccks
haccks

Reputation: 106042

arr_a is a pointer to an array of 5 char while arr_b is an array of 20 chars. arr_b is not a pointer unlike arr_a.

sizeof (*arr_b) equals to sizeof (char) because *arr_b is of type char (equivalent to arr_b[0]). For

sizeof (*arr_a) equals to 5*sizeof(char) because *arr_a refers to an array of 5 chars and sizeof returns the size of array which is 5.

Upvotes: 2

user2371524
user2371524

Reputation:

char (*arr_a)[5];

declares a pointer to a 5-element array of char.

char arr_b[20];

declares just a 20-element array of char.

So, the output of

sizeof (*arr_a)

should be straight forward -- dereferencing the pointer to an array yields the array and it's size is 5.

The following:

sizeof (*arr_b)

gives 1, because dereferencing the identifier of an array yields the first element of that array, which is of type char.


One thing you need to know to fully understand this is how an array evaluates in an expression:

  • In most contexts, the array evaluates to a pointer to its first element. This is for example the case when you apply indexing to the array. a[i] is just synonymous to *(a+i). As the array evaluates to a pointer, this works as expected.

  • There are exceptions, notably sizeof, which gives you the storage size of the array itself. Also, _Alignof and & don't treat the array as a pointer.

Upvotes: 4

Related Questions