Pointer to structure member access

I thought I had this stuff down, but I was writing some code and got an error when compiling. First here is the code you need to know about:
1
2
contributions * members = new contributions[number]  //contributions is a structure;
if (members[i]->amount > 9999)


I thought that if you used new to declare a pointer to structure, you used the -> operator to access its members. But when I did that it didn't compile, so I switched it to a . operator and it works. Why? Did I misunderstand something?

Also, is this a new thing where we can't post help in title. If so, that is a good idea.
I thought that if you used new to declare a pointer to structure, you used the -> operator to access its members.


This is true.

The thing is, you dereference pointers only once. There are 3 different operators that dereference them:

* as in *foo
[] as in foo[0]
-> as in foo->bar

Since you are using [] to dereference your pointer, you use . instead of ->. Using both [] and -> doesn't work because then you'd be dereferencing twice.

1
2
3
4
// all the below are the same:
foo[i].bar;
(foo+i)->bar;
(*(foo+i)).bar;
Last edited on
ah, so if you already have any of those above (*, [], or ->) then you use '.' . Otherwise use the -> .
yes
i didnt know that. or rather, i never thought about what was happening with [] and ->.
Topic archived. No new replies allowed.