in c, i tried to print out address of variable and address of some function. I got one is negative value, the other is positive value. My question is: why does C not represent in all negative or all positive value?
Here is my code:
int foo() {
return 0;
}
int main() {
int a;
printf("%d\n",&a);
printf("%d\n",foo);
return 0;
}
Here is result:
-1075908992 134513684
Memory addresses should not be interpreted as signed integers in that way. The sign of the number depends on the highest bit set (assuming two's complement representation, which is used by the vast majority of systems currently in use), so a memory address above 0x80000000 on a 32-bit system will be negative, and a memory address below 0x80000000 will be positive. There's no real significance to that.
You should be printing memory addresses using the %p
modifier; alternatively, some people use %08x
for printing memory addresses (or %016llx
on 64-bit systems). This will always print out as an unsigned integer in hexadecimal, which is far more useful than a signed decimal integer.
int a;
printf("%p\n", &a);