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.
Actually, you use
p[index].xandp[index].yto access elements of thestructinside an array, because in this case you are using a pointer to refer to a dynamically allocated array.The
ptr->memberoperator is simply a shorthand for(*ptr).member. In order to use it, you need a pointer on the left-hand side:Note that even for a dynamically allocated array the
->operator would have worked:This is equivalent to
because a pointer to an array is equal to the pointer to its first element.