Search code examples
c++cpointersmemoryunsigned-integer

How to work with memory addresses in C? Are they hexadexcimals or unsigned ints?


I am learning C and recently had my class on pointers and memory addresses. The teacher told us that memory locations are basically unsigned numbers, so we can display them using the following code:

int a;
printf("%u", &a);

or

int a, *p=&a;
printf("%u", p);

Indeed, this works, but I also read in some forums that one should use %p or %x for printing addresses. So, they must be hex numbers... Are the integers I am seeing above actually hexadecimal numbers converted to decimal? And what are addresses actually in their basic form - hex or integer or simply binary nos.

Please help me on this.


Solution

  • Addresses in their basic form are simply values. Hex, or binary, or octal are representations of a number. For example, 42, 0x2a, 2a16, 052, 528, 1010102 and 1042 are all different representations of the same value.

    In terms of what you should be using as a format string, %p is the correct one. There is no guarantee that unsigned integers will have the same number of bits as a pointer so you may well lose information.

    In fact, providing and argument to printf that doesn't match the corresponding format specifier is actually undefined behaviour.

    Using %u or %x variants may well work on most systems where pointers and unsigned integers are of a compatible size but truly portable code wouldn't rely on that. For example, an implementation is free to have a 16-bit unsigned integer (to satisfy the minimum range requirements in ISO C11 Appendix E) and a 1024-bit pointer type (I gotta get me one of those machines).