Pointer question

This is a discussion on Pointer question within the C Programming forums, part of the General Programming Boards category; Sounds simple... but why isn't bookPtr = &theBook the same as *bookPtr =theBook?...

  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.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    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, 09:54 AM
  3. char pointer to pointer question
    By Salt Shaker in forum C Programming
    Replies: 3
    Last Post: 01-10-2009, 10:59 AM
  4. Pointer question
    By rakan in forum C++ Programming
    Replies: 2
    Last Post: 11-19-2006, 01:23 AM
  5. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 08:32 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21