Reputation: 2675
Suppose I define this structure:
struct Point {
double x, y;
};
Now, suppose I create a dynamic array of this type:
Point *P = new Point[10];
Why do I use P[k].x
and P[k].y
instead of P[k]->x
and P[k]->y
to access the k
-th point's elements?
I thought you had to use the latter for pointers.
Upvotes: 10
Views: 9593
Reputation: 64
I believe the Q relates to C Indirection
In C, an array name IS a variable of type ( pointer to the first memory location allocated to / for the array )
Specifying an index ( square-bracket notation of, [n]
) results in indirection.
Hence,
PointerA behaves like ArrayA
*PointerA behaves like ArrayA[]
For variables of type pointer, the asterisk (*) is the Indirection Operator used to,
Access the value ( stored WITHIN a memory location )
Given the code example in the original Q, assuming P is assigned to memory-address location ADDR-01
P
refers to ADDR-01
not what's stored WITHIN ADDR-01
P[0]
refers to what's stored WITHIN ADDR-01
thru ADDR-16
with the 1st 8 bytes
of P[0]
being x
and the 2nd 8 bytes
of P[0]
being y
P[0]
occupies ADDR-01 thru ADDR-16 ( 16 bytes ) because a double
is 8 bytes and x and y are both defined as double
Upvotes: -1
Reputation: 227390
Because you have created a dynamically allocated array that holds Point
objects, not Point*
. You access each member via operator[]
:
p[0].x = 42;
Upvotes: 1
Reputation: 2347
In general the arrow ->
operator is used to dereference a pointer. But in this case, P is an array of Points. if P was an array of Point pointers then you would have uses the latter
Upvotes: 1
Reputation: 110658
Why do I use P[k].x and P[k].y instead of P[k]->x and P[k]->y to access the k-th point's elements?
Because P[k]
is not a pointer, it is the object at the k
th position and its type is Point
, not Point*
. For example:
Point p = P[0]; // Copy 0th object
p.x; // Access member x
Point* pp = &(P[0]); // Get address of 0th element, equivalent to just P
pp->x; // Access member x
Upvotes: 1
Reputation: 726489
Actually, you use p[index].x
and p[index].y
to access elements of the struct
inside an array, because in this case you are using a pointer to refer to a dynamically allocated array.
The ptr->member
operator is simply a shorthand for (*ptr).member
. In order to use it, you need a pointer on the left-hand side:
Point *p = new Point;
p->x = 12.34;
p->y = 56.78;
Note that even for a dynamically allocated array the ->
operator would have worked:
Point *p = new Point[10];
p->x = 12.34;
p->y = 56.78;
This is equivalent to
p[0].x = 12.34;
p[0].y = 56.78;
because a pointer to an array is equal to the pointer to its first element.
Upvotes: 13