Reputation: 9
When I create an array
and a pointer to that array
, why cant I print out the numbers by writing *p[3]
instead of just p[3]
. When I am doing it with normal numbers like the variable b
in the example, I can only access the pointers value by typing the *
operator before e
(i.e *e
). And why isn't it int *p = &array
instead of int *p = array
?
#include <iostream>
int main(){
int array[5] = {3, 3, 4, 6, 7};
int *p = array;
std::cout << p << "\n" << p[3];
int b = 5;
int *e = &b;
std::cout << "\n" << e << " " << *e;
}
Upvotes: 0
Views: 112
Reputation: 25116
why cant I print out the numbers by writing
*p[3]
instead of justp[3]
The expression p[3]
is, by definition of the subscript operator []
, equivalent to *(p+3)
, which means that the int
element that exists 3 elements after the element pointed to by p
is retrieved.
Therefore, *p[3]
is equivalent to **(p+3)
, which does not make sense, because *(p+3)
is an object of type int
, which cannot be dereferenced. Only pointers can be dereferenced.
And why isn't it
int *p = &array
instead ofint *p = array
?
In the declaration int *p = array;
, the expression array
will decay to a pointer to the first element of the array, i.e. to &array[0]
. Therefore, p
will point to the first element of the array.
However, if you write int *p = &array;
instead, then array
will not decay to &array[0]
. Instead, the expression &array
will evaluate to a pointer to the entire array, not to a pointer to the first element of the array. This means that the type of the pointer is not int *
(pointer to a single int
), but rather int (*)[5]
(pointer to an array of 5 int
elements). A pointer of type int (*)[5]
cannot be assigned to a pointer of type int *
without an explicit cast. For this reason, the line int *p = &array;
is not valid.
Upvotes: 3
Reputation: 4450
operator[]
dereferences the pointer. You can also get a pointed to value by writing e[0]
. Using both operator[]
and the dereferencing asterisk would dereference twice.
Upvotes: 0