views:

303

answers:

3

In C, we can place "&" before a variable to figure out the address of that variable. I have a 32 bit machine. Whenever I print the address in the console, the console displays a 7 digit base 10 number. I just want to know how's that number (10^7) related to the 32-bit machine. (2^32) Thanks

+13  A: 

You should probably print it out as either a pointer or hex value:

printf ("address = %p\n", &variable);
printf ("address = %x\n", &variable);

This will give you a hex number of up to 8 digits (for your 32-bit address space).

A 32-bit number ranges from 0000000016 through FFFFFFFF16 (0 through 4,294,967,295 in decimal) so it could be up to 10 decimal digits.

The reason you're only getting a 7-digit base-10 number is because your variable is nowhere near the top of the address space.

paxdiablo
+2  A: 

Maximum 32-bit number, 0xFFFFFFFF in hex, translates to 4294967296 (base 10) so you need 10 decimal digits to display the maximum 32-bit number. Lower numbers will use fewer digits (0x1 only requires 1).

Ron Pihlgren
I spot an Obi-Wan ...
unwind
+2  A: 

Where a variable lands in memory has to do with what sort of storage its in (i.e., stack vs static data), and how your executable has mapped those segments into memory.

Try statically allocating an array of 25 million integers, and take the address of the last one .. bet you see a number maybe up nearer 100,000,000. (Don't get too carried away in this vein though, unless you want to see what happens when your system runs out of ram =)

You can do

printf("0x%08x", &whatever)

.. to get the full 8 hex digits with zero padding filled in on the left.

The '0x' part isn't strictly necessary, but it helps avoid confusion if/when, three weeks later, you run the program again and the hex number you happen to be looking at doesn't have an A-F characters in it.

JustJeff
It's better to use the `%p` modifier, which is made specifically for pointers (and by extension, addresses).
Chris Lutz
Or, if you don't like what the native %p does, use a uintptr_t cast and a uintptr_t format - PRIXPTR, for example (from <inttypes.h> in C99).
Jonathan Leffler