问题
#include<stdio.h>
int main(){
int a;
printf("%u\n ",&a);
printf("%p\n ",a);
printf("%p\n ",&a);
printf("%fp\n ",&a);
return 0;
}
I have tried this code but I am not able to understand the output
4193177020
(nil)
0x7ffff9eecdbc
0.000000p
What is semgmented memory address in this and what part is offset?
回答1:
Apparently your a
variable was initialized with 0
.
%u
displays an unsigned integer, and you pass the memory address as an argument%p
usually displays the value of a pointer, so in case of 0 it shows it as(nil)
%p
does the same, but you now pass the address ofa
, which is displayed in hex.%fp
is%f
(float formatting) and a literalp
. I'm pretty sure this one causes undefined behavior since printf expects a float and you pass an integer (pointers are long/integer values).
What do we learn from it? Don't write nonsense code and don't pass arguments to printf-style functions unless you have a format string that expects exactly those arguments.
回答2:
It seems that you are reading some very old book. Segment and offset combinations were used to address memory in 16 bit applications, they were called "far pointers" as opposed to "local pointers" that contained only an offset (segment was typically taken from the ds
register for those).
None of this is relevant any more with 32 bit or 64 bit applications. These applications work with a single block of virtual memory that is no longer subdivided into segments. The operating system takes care of mapping parts of the virtual memory to physical memory, this is something that applications no longer need to worry about. All pointers are simply an offset (32 bit or 64 bit for 32 bit or 64 bit applications respectively) inside that virtual memory space - a single number.
As to your printf
statements, the only one that actually takes the pointer to a
and prints it as a pointer is printf("%p\n ",&a)
- the others are invalid as pointed out by the other answer.
来源:https://stackoverflow.com/questions/21361959/what-will-be-the-output-of-this-please-explain-it-also