scdmb
scdmb

Reputation: 15621

Why doesn't (&array)[i] take the address of the ith element?

Consider the following code

int tab2[2];
tab2[0]=5;
tab2[1]=3;
std::cout << tab2[1] << std::endl;
std::cout << (&tab2)[1] << std::endl;

As I have read in other topics, an array can decay to pointer at its first element. Then why doesn't the [] doesn't work the same for tab2 and &tab2 in the above code? What is different?

Upvotes: 4

Views: 368

Answers (4)

Doug T.
Doug T.

Reputation: 65599

This expression:

(&tab2)[1]

Gets you a pointer to an array of 2 ints. Then uses array syntax on that pointer-to-an-array to get you the 1st 2 element int array after tab2.

So you have in memory

          tab2

          0         1   // index into tab2
          5         3   // values

You get a pointer to the array

          0         1
 &tab2 -> 5         3

Then you go 1 array of 2 ints past tab2

          0         1         2        3
 &tab2 -> 5         3         ?        ?
                             /|\
                              (&tab2)[1]

Upvotes: 3

Macmade
Macmade

Reputation: 53960

It's already "converted" as a pointer. You can use the [] notation with arrays or pointers...

(&tab2) means you get the address of your array... In a pointer perspective, it's a pointer to a pointer ( ** ).

So you are trying to convert a variable (which is an array) as a pointer. Ok, but then you try to access the [1] element, which of course does not exist, as your pointer points to your array's address... Such a notation would expect a second array.

Upvotes: 3

Harsh
Harsh

Reputation: 459

When you use (&tab2), you are retrieving the address of your array. Your statement itself answers your question. Had you used (*(&tab2)), you would have got what you were expecting as output - 3.

Upvotes: 2

MGZero
MGZero

Reputation: 5963

What you've done by adding address-of (&) to tab2 is given yourself the memory address of the tab2 pointer, or a pointer to a pointer (int**). So logically, yes, indexing it makes sense. However, &tab2 is not the same as tab2. &tab2 points to the pointer itsefl, while tab2 points to the array. By indexing &tab2 with 1, you've told it to look at the next element in sequence, which doesn't exist (or it does exist, but belongs to another variable). Had you indexed it with 0, this would have been fine as you would be looking at the "root" of the memory sequence.

Indexing just tab2 is fine as well obviously, because it points to an array.

Upvotes: 0

Related Questions