I'm having a hard time using pointers because I don't understand them that well. When is it correct to use the * and & operator and what do they do?
I'm having a hard time using pointers because I don't understand them that well. When is it correct to use the * and & operator and what do they do?
What have you read about them?I admit some explanations are better than others. Don't give up though.
The & is the address of operator, which fetches the address of some variable. Pointers use this address as a value.
The * is the dereference operator, which fetches the object stored in the pointer's value. In conjunction with this operator you can change the pointed to object. This is useful because you can modify things that weren't given a name, like memory returned from malloc()/calloc()/realloc(). The only time it is not okay to use the * operator is when the pointer is invalid, meaning it doesn't point to a usable address. Such pointers could have the value NULL. It is good practice to NULL pointers that shouldn't be used anymore because otherwise you just don't know and run the risk of invoking undefined behavior.
Last edited by whiteflags; 08-31-2012 at 05:36 PM.
What i would also like to add is that & and * operators kill each other when they are used adjacent to each other(no matter which operator comes first).
Not quite, e.g., if x is an int, then &*x is invalid even though *&x is valid. On the other hand, if p is a pointer to an object, then &*p results in p, except that the operations are not actually evaluated and the result is not an lvalue.Originally Posted by std10093
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)