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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With