When you want a pointer to point to memory address of a variable you use the address operator(&) but when you want a pointer to point to an array you just use the array name without the address operator, why is this?
-
1You *can* use `&` just fine, it's just that [array decaying](https://stackoverflow.com/q/1461432/364696) means if you don't, the array still implicitly decays to a pointer. – ShadowRanger Jul 14 '18 at 01:37
-
Because it is one of the weird things that you just have to get used to about c++ (and c) – DarthRubik Jul 14 '18 at 01:39
-
1You can use either `array` or `&array[0]`, the address of the first element. – stark Jul 14 '18 at 01:39
-
1Because the syntax rules of C++ (and C) specify that using the name of an array in a context where a pointer is expected, gives a pointer to its first element. Using `&array` gives something else (address of the array, not the address of the first element). – Peter Jul 14 '18 at 01:40
-
@Peter Array decay does not depend on names. Any explanation involving "the name of an array" is incorrect. – melpomene Jul 14 '18 at 01:55
2 Answers
The premise is incorrect. If you don't use &, you don't get a pointer to the array; you get a pointer to the first element of the array.
That is:
int arr[] = { 1, 2, 3, 4 };
int *p1 = arr;
int *p2 = &arr[0];
int (*p3)[4] = &arr;
p1 and p2 are equivalent. They both point to the first element of the array, arr[0].
p3 is a pointer to the whole array, and it does need &.
- 84,125
- 8
- 85
- 148
Arrays are implemented as contiguous memory location in the memory. When you write something like
int arr[] = {1, 2, 3};
int *p = arr
Then here arr is just a pointer of base type int pointing to the first element in the array and the [] operator is just helping in its incrementation
e.g.
arr[2]; // same as *(arr+2)
p[2]; // same as *(p+2) i.e. arr[2]
As @melpomene mentioned your question is not wholly correct. A pointer to an array implies something like
int (*p)[3] = &arr;
Here the pointer has a base type of int [3], so when you increment (p++), then p would increment by 3 int.
Pointers to arrays are more visible in case of multi dimensional arrays
- 962
- 10
- 30