I'm trying to wrap my head around pointers, references and addresses but every time I think I got it something unexpected pops up.
Why don't we need to dereference the structure to set a value in this example?
// pointer_tet.cpp
#include <iostream>
struct example
{
char name[20];
int number;
};
int main()
{
using namespace std;
example anExample = {"Test", 5};
example * pt = &anExample;
pt->number = 6;
cout << pt->number << endl;
int anotherExample = 5;
int * pd = &anotherExample;
*pd = 6;
cout << *pd << endl;
return 0;
}
Thanks!
Edit: Thank you for your answers! What confused me was not being able to set *pt.number = 6.
asked Mar 13, 2013 at 20:03
Q-bertsuit
3,4678 gold badges39 silver badges68 bronze badges
2 Answers 2
You are dereferencing pt. You are doing:
pt->number = 6;
This is equivalent to:
(*pt).number = 6;
The -> operator provides a convenient way to access members through a pointer.
answered Mar 13, 2013 at 20:05
Joseph Mansfield
111k22 gold badges249 silver badges329 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Q-bertsuit
Thank you! I read this the other day, but it already slipped my mind. Thanks! Edit: I have to wait 10 min to set answer
Yakk - Adam Nevraumont
The trick here is that
*pt.number is *(pt.number) -- way back in the day, the precedence of * was set awkwardly, and -> was added to make up for having to type (*pt).number all the time.You can do
anExample.number = 6;
OR
(*pt).number = 6;
Read cplusplus.com pointer tutorial might help.
David G
97.6k41 gold badges173 silver badges258 bronze badges
Comments
lang-cpp
pt.