Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Structure Reference and Dereference Operators

Tags:

c++

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.

like image 845
wjm Avatar asked Nov 20 '12 15:11

wjm


People also ask

What is the use of dereference operator?

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.

What is reference and dereference operator in Arduino?

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.

What is dereference in C++ with example?

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.

What is the reference operator in C++?

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;.


1 Answers

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.

like image 90
Sergey Kalinichenko Avatar answered Oct 16 '22 06:10

Sergey Kalinichenko