Thread: Pointer question

  1. #1
    Registered User
    Join Date
    May 2009

    Pointer question

    Sounds simple... but why isn't bookPtr = &theBook the same as
    *bookPtr =theBook?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Because changing what a pointer points to and changing the value of what a pointer points to are two different things.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Oct 2009
    I dont think so these statements are same
    because first case is correct you are giving address to the pointer but second case is not correct actually.

  4. #4
    Registered User
    Join Date
    Nov 2009
    bookPtr = &theBook
    This makes only sense if bookPtr was declared as a pointer:

    char * bookPtr;
    id * bookPtr;
    The first example declares a pointer that can hold the address of a char (otherwise said: a pointer to char). The second variant is the declaration of a pointer to int. Thus the asterisk * is used here to declare a pointer.
    These statements just declare bookPtr as a variable that can hold an address. Let's assume that you declared it as a pointer to id. Then

    int theBook = 67;
    bookPtr = &theBook
    declares theBook as an int and stores the value 67 in it. The second line makes bookPtr point to the address of theBook.
    Now, the second statement:

    *bookPtr =theOtherBook
    Here the asterisk is used as a "derefence operator", meaning "the variable where bookPtr points to". We gave it the address of theBook in the previous code-block. Now we are giving this variable (theBook) the value of another variable: theOtherBook.

    So, we changed he value of theBook in an indirect way, namely via its pointer. The dereference operator * is therefore also called "indirection operator".

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sorting number
    By Leslie in forum C Programming
    Replies: 8
    Last Post: 05-20-2009, 04:23 AM
  2. Easy pointer question
    By Edo in forum C++ Programming
    Replies: 3
    Last Post: 01-19-2009, 10:54 AM
  3. char pointer to pointer question
    By Salt Shaker in forum C Programming
    Replies: 3
    Last Post: 01-10-2009, 11:59 AM
  4. Pointer question
    By rakan in forum C++ Programming
    Replies: 2
    Last Post: 11-19-2006, 02:23 AM
  5. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM