简体   繁体   中英

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

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 */

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.

Be wary of the types.

  • The type of myArray is int[10] .
  • The type of &myArray is int (*)[10] (pointer to int[10] ).
  • When evaluated, the type of myArray is int * . Ie the type of the value of myArray is int * .
  • sizeof does not evaluate its argument. Hence sizeof(myArray) == sizeof(int[10]) != sizeof(int *) .

Corollary:

  • myArray and &myArray are incompatible pointer types, and are not interchangeable.

You cannot correctly assign &myArray to a variable of type int *foo .

An array is not a pointer. However, if an array name is used in an expression where it is not the subject of either the & operator or the sizeof operator, it will evaluate to a pointer to its first element.

No, an array is that first element (and the rest). It doesn't get converted into a pointer until you pass it as an argument to a function.

arrayname will point to all the elements of the array. That is the reason you can do (arrayname + 5) to point to the 5th element in the array.

arrayname不是指针,但可以将其视为指向数组第一个元素的指针。

做arrayname ++,你会知道arrayname一次代表整个数组而不仅仅是起始元素....默认情况下它保留了第一个元素的起始地址

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM