0

I have written the following in C, and would like to retrieve the address of the variable x:

    int x = 10;
    int *address_of_x = &x;
    printf("The address of x is: %s \n", address_of_x);
    printf("The value of x is: %i \n", *address_of_x);

In this case, where I put %s, I don't get any value. If I change it to %i, I get an integer value. I was expecting the address to be like having a mix of numbers and letters. So, does the letter following % matter here, which seems does?

What should I do in this case to get the address of the variable x?

Thanks.

Joshua Taylor
  • 84,998
  • 9
  • 154
  • 353
  • `%s` means: Take that pointer, interpret it as a `char *`, and print the text it points at. `%i` means: Take that `int` and print it in base 10. Both are wrong when you pass an `int *`. –  Jun 04 '14 at 17:58

2 Answers2

2

Try instead:

printf("The address of x is: %p \n", (void*)address_of_x);

%p here stands for pointer, for some more of these identifier you can look here

i.e. %x shows the address as a nice hex number

Lorenzo Boccaccia
  • 6,041
  • 2
  • 19
  • 29
Iowa15
  • 3,027
  • 6
  • 28
  • 35
  • Thanks for your reply. What does `(void*)` mean? –  Jun 04 '14 at 18:03
  • 1
    Trying to print an address with `%x` might give you a surprise in a 64-bit program with 32-bit integers. – Mark Ransom Jun 04 '14 at 18:13
  • @medcompsweng You really don't need the (void*), but technically, printf requires a pointer of type (void*). A void pointer is essentially a pointer that can represent any data type (you can look more about this). So by putting that cast there, we just ensure that printf is getting the type it is supposed to. – Iowa15 Jun 04 '14 at 20:46
1
printf("The address of x is: %p \n", &x);
SteveL
  • 3,331
  • 4
  • 32
  • 57