Reputation: 2315
I am trying to find the address location in C of a specific variable now I try to write a code which is this :
#include<stdio.h>
int main()
{
int g = 3;
printf("%p %d %u ",&g,&g,&g);
return 0;
}
now I am confused that why is GCC compiler is giving me warning using these :
Warnings are
warning: format '%d' expects type 'int', but argument 3 has type 'int *'
warning: format '%u' expects type 'unsigned int', but argument 4 has type 'int *'
Also the answers are quite amazing
0xbfa5953c -1079667396 3215299900
Now my question is which would I accept as a location to my number
Upvotes: 0
Views: 141
Reputation: 754440
Assuming you can use C99, you could use:
#include <stdio.h>
#include <inttypes.h>
int main(void)
{
int g = 3;
printf("%p %" PRIdPTR " %" PRIuPTR "\n", &g, (intptr_t)&g, (uintptr_t)&g);
return 0;
}
All the numbers are equivalent in the sense that they represent the same bit pattern as the address. Hex tends to be the preferred notation for addresses, but octal (not shown) has a long history too (but requires even more digits than decimal).
Upvotes: 0
Reputation: 437514
The expression &g
evaluates to the same value (bitwise) in every case. It's just a matter of how those bits should be interpreted.
So it turns out that 0xbfa5953c (hex) == 3215299900 (dec), which is hardly surprising. The negative value is meaningless because a memory address is not a signed integer.
Upvotes: 4
Reputation: 23876
1st one is correct location - the other if printed as unsigned hex will give you the same value too.
Note this is not the exact (or even close) location in physical memory - because almost all modern OS's use virtual addressing now.
Upvotes: 0