Archived

This topic is now archived and is closed to further replies.

Pointers and such...

This topic is 5816 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Yes, I know this is a very basic question, but I wanted to know more for clarification, since I see things done two ways. If you do this: int bob; int *x; // x is a pointer to an integer x = &bob; // x points to address of bob Is that the same as this: int bob; int *x = &bob / x points to address of bob Or do those mean two different things? And if you do this: int tom; int *x = &tom; Would *x hold the address of tom, and x hold the value of tom? Is that correct? And would changing x to 27 make tom 27, or changing tom to 100, make x 100? Any clarification on these things would be helpful. While programming in C, what do the -> operators mean? I don''t really know what they are called, so I can''t look up information on them. Thanks all. I am not worthy of a sig!

Share this post


Link to post
Share on other sites
int bob;
int * x;
x = &bob;

is the same as

int bob;
int * x = &bob;

it just saves a line of code

x holds the address of bob and *x holds the value of bob. Think of * as ''contents of'' when dereferencing a variable. Remember, x is a pointer, so it only holds an address.

D

Share this post


Link to post
Share on other sites
Drakkor is totally right, but just to clarify your second question:

int tom;
int *x = &tom;

It might look, as you thought, like *x is holding the address of tom, but it''s not. In this instance you''re using the * to declare the pointer not to dereference it, so as usual x will hold the address and *x will hold the value.

The -> is called "pointer to member notation," it might have some other names too but that''s what I''ve seen it called. If you have a pointer to a struct or an object you use -> to simultaneously dereference it and access its fields and methods. So if class CObject has field foo and method bar:

CObject myObj= new CObject();
myObj->foo = myObj->bar();

instead of something like:

CObject myObj = new CObject();
(*myObj).foo = (*myObj).bar();

Share this post


Link to post
Share on other sites