Structure links and dereferencing operations

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 elements?

I thought you need to use the latter for pointers.

+6
source share
4 answers

In fact, you use p[index].x and p[index].y to access struct elements inside an array, because in this case you use a pointer to refer to a dynamically allocated array.

The ptr->member operator is simply a shorthand for (*ptr).member . To use it, you need to specify the pointer on the left side:

 Point *p = new Point; p->x = 12.34; p->y = 56.78; 

Note that even for a dynamically allocated array, a -> operator would work:

 Point *p = new Point[10]; p->x = 12.34; p->y = 56.78; 

It is equivalent

 p[0].x = 12.34; p[0].y = 56.78; 

because the pointer to the array is equal to the pointer to its first element.

+11
source

Since you created a dynamically allocated array containing Point objects, not Point* . You get access to each member through operator[] :

 p[0].x = 42; 
+1
source

Why to access the elements of the k-th point? P /

Since P[k] not a pointer, it is an object at position k th, and its type is Point , not Point* . For instance:

 Point p = P[0]; // Copy 0th object px; // Access member x Point* pp = &(P[0]); // Get address of 0th element, equivalent to just P pp->x; // Access member x 
+1
source

In general, the arrow operator -> 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 use the last

+1
source

All Articles