Using pointers to print memory address

Discussion in 'Programmer's Corner' started by asilvester635, Feb 11, 2017.

  1. asilvester635

    Thread Starter Member

    Jan 26, 2017
    68
    3
    I was just curious. Why don't this print the memory address that both x and b are pointing to? From my understanding the & is suppose to return a pointer (memory address), so why can't I print that address?

    Code (Text):
    1.  
    2. int x = 7;
    3.     int* b = &x;
    4.  
    5.     printf("%d\n", &b);
    6.  
     
  2. Papabravo

    Expert

    Feb 24, 2006
    10,836
    2,033
    Types, types, types. The format specifier %d in the first argument of the printf function call implies that &b IS AN INTEGER. So let me ask you this question: Is &b an integer? The answer has a sensitive dependence on the compiler and the target machine. What would you do on an x86 machine where a pointer was actually expressed as a segment and an offset, each 16 bits long?

    If you drill down into the assembly language code produced by the compiler you will find that &b is on the top of the stack. printf will take an integers worth of data from the top of the stack and print that value. It might be instructive to learn about the sizeof operator and compare sizeof(int) and sizeof(int*). This might be the first of many surprises.
     
  3. asilvester635

    Thread Starter Member

    Jan 26, 2017
    68
    3
    Thanks for pointing that out. I found that %p is to print the pointer address stored in the pointer.
     
  4. WBahn

    Moderator

    Mar 31, 2012
    19,291
    5,230
    What is it you are trying to print out?

    Do you want the value 7?
    Do you want the address where the 7 is stored?
    Do you want the value stored in b?
    Do you want the address where b is stored?

    The code that you have is dangerous in that it can corrupt the stack. The %d specifier tells printf() to read a number of bytes from the stack equal to the number of bytes needed to store a signed integer and then interpret those bytes as a signed integer. But &b is a pointer and so the number of bytes corresponding to a pointer will be pushed onto the stack. If the size of a pointer is different than the size of a signed integer (and on many compilers it isn't, they are both 32 bits, but on an increasing number of compilers a pointer is 64 bits), you have a mismatch and the behavior becomes undefined.
     
  5. asilvester635

    Thread Starter Member

    Jan 26, 2017
    68
    3
    address where b is stored.
     
Loading...