Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Isn't an array/arrayname always a pointer to the first element in C?

Tags:

arrays

c

pointers

What's going in below isn't an arrayname always a pointer to the first element in C?

int myArray[10] = {0};

printf("%d\n", &myArray); /* prints memadress for first element */
printf("%d\n", myArray); /* this prints a memadress too, shows that the name is a pointer */

printf("%d\n",sizeof(myArray)); /* this prints size of the whole array, not a pointer anymore? */
printf("%d\n",sizeof(&myArray)); /* this prints the size of the pointer */
like image 326
Chris_45 Avatar asked Dec 04 '09 08:12

Chris_45


1 Answers

Array name is array name. Array name is an identifier that identifies the entire array object. It is not a pointer to anything.

When array name is used in an expression the array type gets automatically implicitly converted to pointer-to-element type in almost all contexts (this is often referred to as "array type decay"). The resultant pointer is a completely independent temporary rvalue. It has nothing to do with the array itself. It has nothing to do with the array name.

The two exceptions when the implicit conversion does not take place is: operator sizeof and unary operator & (address-of). This is exactly what you tested in your code.

like image 131
AnT Avatar answered Sep 18 '22 21:09

AnT