Thread: FAQ '&' and '*' (C++)

  1. #1
    Registered User
    Join Date
    Oct 2001
    Posts
    101

    '&' and '*'

    I'm always confusing with the '*' and '&' in C++. Would anyone mind telling me the differences before them? Does any website talk about '*' and '&'? Thank you!~

  2. #2
    Registered User
    Join Date
    Sep 2001
    Posts
    156
    When defining a pointer we use *:
    int * pI = NULL;
    char* pC = NULL;
    in the above case both pointers have been set to NULL or do not point to anything.

    The & is reference to or address of, so below:
    int i =0; //i = 0
    char c = ' ';c = a space ' ';

    pI = &i;
    pC = &c;

    we assign the address of i to pointer pI and the address of c to Pc. Now we can use the * to dereference our pointers, which is to get the value of the item they point to:

    int t = *pI; this expression will resolve to setting t to 0 because pI points to i and i == 0.
    *pI = 10; this expression will resolve to setting i to 10 because pI points to i.

    char ch = *pC; this expression will resolve to to assigning ' ' (a space) to ch.
    *pC = 'A'; this expression will resolve to setting c to 'A'.

    now comes the wacky part of a & ( reference ). I can define a reference to i;

    int &rI = i; //rI will always equal i and vice a versa

    The reference (&) is like a constant pointer that is automathically dereferenced. It is usually used for function argument lists and function return values.

    I hope that helps. For more info I would recommend reading "Thinking in C++ second edition" by Bruce Eckel.

Popular pages Recent additions subscribe to a feed