quick pinter question

This is a discussion on quick pinter question within the C Programming forums, part of the General Programming Boards category; hell if i do this, it's all good: Code: int x = 9; int* ptr; ptr = &x; printf("%d",*ptr); but ...

  1. #1
    Registered User
    Join Date
    Sep 2005
    Posts
    84

    quick pinter question

    hell

    if i do this, it's all good:

    Code:
          int x = 9;
          int* ptr;
          
          ptr = &x;
          
          printf("%d",*ptr);
    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:

    Code:
          int x = 9;
          int* ptr;
          
          ptr = x;
          
          printf("%d",*ptr);

  2. #2
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    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
    Posts
    6,656
    &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 Cprogramming.com
    Replies: 8
    Last Post: 10-27-2005, 12:05 AM
  2. very quick question.
    By Unregistered in forum C++ Programming
    Replies: 7
    Last Post: 07-24-2002, 04:48 AM
  3. quick question
    By Unregistered in forum C++ Programming
    Replies: 5
    Last Post: 07-22-2002, 05:44 AM
  4. Quick Question Regarding Pointers
    By charash in forum C++ Programming
    Replies: 4
    Last Post: 05-04-2002, 12:04 PM
  5. Quick question: exit();
    By Cheeze-It in forum C Programming
    Replies: 6
    Last Post: 08-15-2001, 06:46 PM

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