Jump to content

  • Log In with Google      Sign In   
  • Create Account

Pointer Help


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
2 replies to this topic

#1 Mia.   Members   -  Reputation: 494

Like
1Likes
Like

Posted 28 April 2014 - 05:37 PM

I have searched the internet over and asked around for a good explanation of the difference between the following symbols in C++: -> , * , and & . I have a vague concept of each (I use them occasionally), but nothing concrete. Can someone please explain this to me in uncomplicated terms, possibly with an example of the appropriate use of each? I would greatly appreciate it!



Sponsor:

#2 ApochPiQ   Moderators   -  Reputation: 16396

Like
16Likes
Like

Posted 28 April 2014 - 05:50 PM

Let's start with &.

& is the "get address" operator. This turns something (like, say, an int) into a pointer to that something:

int value = 42;
int * pointer = &value;
Now that we have a pointer, we need a way to find out what it points at. That's where * comes it - it's like the reverse of &. I like to think of it as "follow":

int newValue = *pointer;
Note that I can either read from or write to the result of dereferencing a pointer:

*pointer = 33;

Now, suppose the thing we're pointing to is a class or structure. Then I can use -> as a shorthand for (*pointer).member, like this:

struct Foo {
    int Number;
    bool Flag;
};

Foo obj;
obj.Number = 42;
obj.Flag = true;

Foo * pointer = &obj;

pointer->Flag = false;

// Exactly the same effect:
(*pointer).Flag = false;
Note that in C++ you can use -> in more complex ways, but that can come later. In general there's a lot of stuff possible with pointers, but hopefully those few basic elements will get you started!

#3 catslap   Members   -  Reputation: 35

Like
0Likes
Like

Posted 30 April 2014 - 03:50 PM

it helps a lot to write a small program which has a variable, set it then printfs each of the options to the output. Then nose at the debugger for the value, the location etc, get your head around it properly.






Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS