Provided that texts
is an array of 3 strings, what's the difference between &texts[3]
and (&texts)[3]
?
Asked
Active
Viewed 95 times
0
-
1Please read about [mcve]. "an array of 3 strings" could be many things – 463035818_is_not_an_ai Jan 11 '21 at 18:54
-
1C question, but C and C++ are close enough here for [What's the difference between array and &array?](https://stackoverflow.com/questions/30194630/whats-the-difference-between-array-and-array) to be good reading. – user4581301 Jan 11 '21 at 18:54
-
The keyword you are looking for is [operator precedence](https://en.cppreference.com/w/cpp/language/operator_precedence). – Lukas-T Jan 11 '21 at 18:54
-
1@user4581301 Not sure that your suggested 'dupe' actually addresses the difference in the `[3]` operation on the two *different* pointer types. – Adrian Mole Jan 11 '21 at 18:57
-
1@AdrianMole Not a dupe or I would have closed the question. Just useful reading. The answer can be inferred from the reading, though. – user4581301 Jan 11 '21 at 18:59
-
1Both won't work as both values point at locations that are not part of memory you allocated. `&texts[3]` is a pointer to the element past the end of the array which could be useful in some cases, but you shouldn't dereference it, the other one treats `texts` as the first element of a array of arrays of strings and accesses the fourth of those. – fabian Jan 11 '21 at 18:59
1 Answers
1
The []
subscript operator has a higher precedence than the &
address-of operator.
&texts[3]
is the same as &(texts[3])
, meaning the 4th element of the array is accessed and then the address of that element is taken. Assuming the array is like string texts[3]
, that will produce a string*
pointer that is pointing at the 1-past-the-end element of the array, ie similar to an end
iterator in a std::array
or std::vector
.
----------------------------
| string | string | string |
----------------------------
^
&texts[3]
(&texts)[3]
, on the other hand, takes the address of the array itself, producing a string(*)[3]
pointer, and then increments that pointer by 3 whole string[3]
arrays. So, again assuming string texts[3]
, you have a string(*)[3]
pointer that is WAY beyond the end boundary of the array.
---------------------------- ---------------------------- ----------------------------
| string | string | string | | string | string | string | | string | string | string |
---------------------------- ---------------------------- ----------------------------
^ ^
&texts[3] (&texts)[3]

Remy Lebeau
- 555,201
- 31
- 458
- 770