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.
Dereference operator. The dereference operator or indirection operator, sometimes denoted by ". * " (i.e. an asterisk ), is a unary operator (i.e. one with a single operand) found in C -like languages that include pointer variables. It operates on a pointer variable, and returns an l-value equivalent to the value at the pointer address.
The reference (&) and dereference operators (*) in Arduino are similar to C. Referencing and dereferencing are used with pointers. If x is a variable, then its address is represented by &x. Similarly, if p is a pointer, then the value contained in the address pointed to by p is represented by &p.
This is called "dereferencing" the pointer. For example, the C code assigned 1 to variable x by using the dereference operator and a pointer to the variable x . The unary * operator, as defined in C and C++, can be used in compositions in cases of multiple indirection, where multiple acts of dereferencing are required.
This sign is called the reference operator. If the reference operator is used you will get the “address of” a variable. In the example above we said: ptr_p = &x;.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With