Reputation: 3437
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.
Upvotes: 1
Views: 103
Reputation: 363
You can do
anExample.number = 6;
OR
(*pt).number = 6;
Read cplusplus.com pointer tutorial might help.
Upvotes: 0
Reputation: 110658
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.
Upvotes: 8