1

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
3
  • 1
    I don't see anywhere you don't dereference to set a value. Commented Mar 13, 2013 at 20:05
  • 2
    Umm, you are dereferencing pt. Commented Mar 13, 2013 at 20:05
  • where do you think you do not derefrence? Commented Mar 13, 2013 at 20:06

2 Answers 2

8

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
Sign up to request clarification or add additional context in comments.

2 Comments

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

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
answered Mar 13, 2013 at 20:10

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.