Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
836 views
in Technique[技术] by (71.8m points)

memory address positive or negative value in c?

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
",&a);

    printf("%d
",foo);

    return 0;
}

Here is result:

-1075908992 134513684
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
", &a);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...