-2

When I tried printing out address of variable in C to my standard output in hexadecimal format, I got a 6 digit answer to my surprise. Since, I work on a 64 bit machine, I expected to have a 16 digit long address since 2^{64} = 16^{16} but instead the address was just 6 digits long.

Code for reference:

#include<stdio.h>

int square();

int x;

int main(){
    scanf("%d",&x);
    printf("%d\n",square());
    printf("\naddress of x is %x",&x);
    return 0;
}

int square(){
    return x*x;
}

The output was: address of x is 407970

Waqar
  • 8,558
  • 4
  • 35
  • 43

1 Answers1

4

First of all printf("\naddress of x is %x",&x); is incorrect. %x expects an unsigned int.

The correct format specifier to print address is %p (more here):

printf("\naddress of x is %p",&x);

//To be more precise cast to void*, see @Gerhardh's comment below
printf("\naddress of x is %p", (void*)&x);

Why is the length of address of variable only 6 digits in hex code although my machine is 64 bit?

unsigned long x = 10;
printf("%lu", x); //prints 10

x is 10 in the above example. Does it mean x is now 8 bit wide? No. Similarly there is a range of addresses starting from 0, the address doesn't have to be big enough to be represented as full 64 bit always. You can assume it to be 0x00407970 in your case.


Side note: The following will have undefined behaviour if the value of x is large. Just enter 123123 as input and see what happens

int square(){
    return x*x;
}
Waqar
  • 8,558
  • 4
  • 35
  • 43
  • 2
    To be more precise, `%p` expects to get a `void` pointer. You should cast the parameter to `(void *)` when passing to `printf`. Without a proper parameter list, no implicit conversion of the pointer will happen. – Gerhardh Jul 09 '20 at 09:02