sunp
sunp

Reputation: 19

Print the address of a variable in memory

#include<stdio.h>
main() {
    int i=9;

    printf("\nAddress of i = %d", &i);
    printf("\nAddress of i = %x", &i);
    printf("\nAddress of i = %u", &i);
    printf("\nAddress of i = %p", &i);
    printf("\nValue of i = %d",i);
}

When I use %p I get: Value of i = 0xbfd08d5c
Other formats %d,%x,%u don't work.

Upvotes: 1

Views: 1117

Answers (2)

lxg
lxg

Reputation: 226

address is a positive integer, therefore, using "%u" , i.e., unsigned int, can print the correct address value.

p.s., "%p" in hexadecimal format and "%u" in common decimal format.

Upvotes: -1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

In general, you are not allowed to use %d, %x, or %u for an address. You should use only %p - that is the only valid format to use for pointers.

Moreover, since %p expects a void pointer, you need to add a cast to &i operation:

printf("\nAddress of i = %p", (void*)&i);

Although the code would work without a cast on most platforms, it is a good idea to add a cast to guarantee compatibility with platforms where a pointer to an int and a void pointer have different representations. I am not sure if there are any such platforms, but the standard does not prohibit them.

Upvotes: 5

Related Questions