by kevin_clever · 9y ago · 0 comments
#include<stdio.h>
int main(int argc, char** argv)
{
char *p;
char c;
int x;
printf("char p %p\n", &p);
printf("char %p, offset %i\n", &c, (int)((void*)&c-(void*)&p));
printf("integer %p, offset %i\n", &x, (int)((void*)&x-(void*)&p));
return 0;
}
Output on `gcc main.c; ./a.out` char p 0x7ffc5107dff0
char 0x7ffc5107dfeb, offset -5
integer 0x7ffc5107dfec, offset -4The C standard is not the final say on things, your compiler and platform are. The standard is merely the minimum specifications that are ideally to be supported on all platforms, however you will still be unpleasantly surprised if you rely on it as such.
What about kernels (Linux, Windows — doesn't matter)... how do you compare physical address pointer with virtual address pointer?
Sure, they have values. But that might not mean much. Pointers can point to entirely different address spaces.
The C language standard defines (pretty imperfectly in the case of processors with multiple address spaces like the 8051 scratchpad RAM) something like a least common denominator you can rely on to "write portable C".
But that's not truth, nor is "portable C" the goal to all engineering efforts. Pointers are numbers. Scratchpad registers can't have pointers taken to them. Those are truths, even if inconvenient.
(The only in any case not-undefined way of calculating some sort of difference value between such is with the use of the optional uintptr_t, but I'd guess this isn't a sort of undefined behaviour which triggers unwanted compiler tricks, anyway.)
[1] Spaceship operator. Think "return value of memcmp" but generalized to any operand types.
(Edit: and for any pointers that you can compare for ordering, you may also calculate their offset from one another. However, like GP said, in practice you can do that for any pointers on common platforms.)
Second: separate variables don't have to appear in memory in source code order. This applies only to struct members, which do.