Structure Reference and Dereference Operators

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.


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 kth 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

Because you have created a dynamically allocated array that holds Point objects, not Point*. You access each member via operator[]:

p[0].x = 42;

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

Tags:

C++