Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

arrays

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?

like image 580
scdmb Avatar asked Feb 22 '23 20:02

scdmb


1 Answers

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.

like image 106
Macmade Avatar answered Mar 08 '23 18:03

Macmade