Thread: quick pinter question

  1. #1
    Registered User
    Join Date
    Sep 2005

    quick pinter question


    if i do this, it's all good:

          int x = 9;
          int* ptr;
          ptr = &x;
    but if i remove that & from in front of that x... it's all bad, can someone tell me why? what am I doing to my pointer by removing the &

    no ampersand code:

          int x = 9;
          int* ptr;
          ptr = x;

  2. #2
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    ptr holds the address of another variable
    & is the "address of" whch gives you a pointer

    So the second one doesn't work because it trying to assign an integer to a pointer instead assigning a pointer to a pointer

  3. #3
    Registered User
    Join Date
    Jun 2005
    &x is the notation for computing the address of x. Pointers typically store an address, hence the assignment "ptr = &x;" is a valid assignment but "ptr = x;" is not.

    In your example, removing the ampersand means you're trying to assign the value integer value 9 to the pointer ptr. Compilers tend to complain about this rather bitterly (as you're trying to do a conversion from an integer to a pointer) as an address with a value 9 has no general meaning. If it was allowed (and it is possible to force the compiler to shut up about the conversion by using a cast), then computing *ptr (derefering ptr) would yield undefined behaviour. Undefined behaviour is usually undesirable as it means anything is allowed to happen, including a program crash. In your example, it probably means junk would be printed.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Very quick math question
    By jverkoey in forum A Brief History of
    Replies: 8
    Last Post: 10-26-2005, 11:05 PM
  2. very quick question.
    By Unregistered in forum C++ Programming
    Replies: 7
    Last Post: 07-24-2002, 03:48 AM
  3. quick question
    By Unregistered in forum C++ Programming
    Replies: 5
    Last Post: 07-22-2002, 04:44 AM
  4. Quick Question Regarding Pointers
    By charash in forum C++ Programming
    Replies: 4
    Last Post: 05-04-2002, 11:04 AM
  5. Quick question: exit();
    By Cheeze-It in forum C Programming
    Replies: 6
    Last Post: 08-15-2001, 05:46 PM