Chris_45
Chris_45

Reputation: 9063

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

Upvotes: 6

Views: 2193

Answers (7)

prakash
prakash

Reputation: 1

do arrayname++ and u will come to know that arrayname at a time represents the whole array and not only the starting element....by default it keeps the starting address of the first element

Upvotes: 0

Alex Budovski
Alex Budovski

Reputation: 18456

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 *. I.e. 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.

Upvotes: 5

caf
caf

Reputation: 239341

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.

Upvotes: 4

AnT stands with Russia
AnT stands with Russia

Reputation: 320777

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.

Upvotes: 18

Christian
Christian

Reputation: 4342

An arrayname is not a pointer, but it can be treated as a pointer to the first element of the array.

Upvotes: 0

aJ.
aJ.

Reputation: 35490

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.

Upvotes: 1

Carl Smotricz
Carl Smotricz

Reputation: 67820

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.

Upvotes: 3

Related Questions