pointers?

so i have been trying to grasp the concept of pointers and reference for some time, and so i thought i should check if i have understood the main stuff about them.

is this correct:

-& is a reference operator, wich obtains the adress of a variabel.
-* is the pointer operator, wich directly changes the value of a variable, rather than making a copy of it, if it say was to be passed from one function to the other.

if this is correct, where would this be really usefull?
and does the "->" have anything to do with pointers?
You're correct about &, although it is called the address-of operator.

* is the dereference operator. It is used on a pointer to refer to the value it points to instead of its memory address; for example,

1
2
int* ptr = &some_int; //ptr contains the address of some_int
*ptr = 5; //some_int is now 5 


* is also used to declare a pointer, just like & is used to declare a reference, but these uses are entirely separate from those above.

The -> operator is used when a pointer points to an object with data or function members. For example,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class A
{
public:
    int a;
};

int main()
{
    A a;
    A* ptr = &a;
    a.a = 5; //int a is 5
    ptr->a = 7; //int a is 7
    //ptr.a = 8; //compiler error
    //*ptr.a = 9; //compiler error; a is not a pointer
    (*ptr).a = 10; //int a is 10, but this syntax is ugly; use -> instead
}
Last edited on
ah ok thanks for clearing that up for me, pointers have been a pain to learn (dont know why really, just couldn't get the info to stick)
Topic archived. No new replies allowed.