Marius
Marius

Reputation: 59

Difference between array and &array[0]

int array[] = {1,2,3,4};

As I understand, array is just a pointer to &array[0]

But how come then sizeof(array); knows size of an array and not just that it's only 4 byte number?

Upvotes: 6

Views: 2687

Answers (5)

John Bode
John Bode

Reputation: 123458

Except when it is the operand of the sizeof or unary & operators, or is a string literal being used to initialize another array in a declaration, an expression of type "N-element array of T" will be converted ("decay") to an expression of type "pointer to T, and the value of the expression will be the address of the first element of the array.

Arrays in C don't store any metadata about their size or anything else, nor is any storage set aside for any sort of pointer. They're laid out pretty much as follows:

     +---+
arr: | 1 | arr[0]
     +---+
     | 2 | arr[1]
     +---+
     | 3 | arr[2]
     +---+
     | 4 | arr[3]
     +---+

There's no separate storage for a variable arr apart from the array elements themselves. As you can see, the address of arr and the address of arr[0] are the same. This is why the expressions arr, &arr, and &arr[0] all give you the same value (the address of the first element), even though the types of those expressions are different.

Except when the operand is a variable-length array, the result of sizeof is computed at compile time, and the compiler treats array operands as arrays in those circumstances; otherwise, it treats the array expression as a pointer to the first element.

Upvotes: 4

ameyCU
ameyCU

Reputation: 16607

In this declaration -

int a[] = {1,2,3,4};    // a is of array type 

a becomes a pointer to first element of array a ( after decay ). Not in all cases both will be equal , but in cases such as when array is passed to function .

Upvotes: 0

Yannick Widmer
Yannick Widmer

Reputation: 1363

This does only work within the scope where you define the array. If you pass your array to a function the sizeof operator doesn't work anymore. I'm not completely sure but I think that the compiler stores the length of the array and puts it back where you have sizeOf(array) like a macro but not dynamically. Please correct me if someone knows better.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726559

Although the name of the array does become a pointer to its initial member in certain contexts (such as passing the array to a function) the name of the array refers to that array as a whole, not only to the pointer to the initial member.

This manifests itself in taking the size of the array through sizeof operator.

Upvotes: 7

Jens Gustedt
Jens Gustedt

Reputation: 78903

No, array is not just a pointer, as your sizeof example shows. It is only that in most contexts, it is converted to &array[0], but not in all.

Upvotes: 0

Related Questions