Alex Rivera | Logout

memory address positive or negative value in c?

Asked 2009-11-06T18:29:48.573
12

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
Edit
Report

2 Answers

40

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);
answered 2009-11-06T18:32:36.730
4

You're printing out in decimal. You probably want to print out the memory location in hexadecimal (using "%p") (most memory addresses are shown in hexadecimal by convention).

answered 2009-11-06T18:32:53.437

Your Answer