We just did a lesson of C on pointers and I had trouble running the example code on my linux machine (Mint 17 64 bit) though it's running fine on Windows 7 (32 bit). The code is as follows:
#include <stdio.h>
int main() {
int var = 20; //actual variable declaration
int *ip; //pointer declaration
ip = &var; //store address of var in pointer
printf("Address of var variable: %x\n", &var);
//address stored in pointer variable
printf("Address stored in ip variable: %x\n", ip);
//access the value using the pointer
printf("Value of *ip variable: %d\n", *ip);
return 0;
}
The program runs as expected on windows with the code blocks ide, but on linux trying to compile in the terminal using GCC I get the following error:
pointers.c: In function ‘main’:
pointers.c:9:2: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int *’ [-Wformat=]
printf("Address of var variable: %x\n", &var);
^
pointers.c:12:2: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int *’ [-Wformat=]
printf("Address stored in ip variable: %x\n", ip);
^
I'd like to know what's going on and how I can get the code to run on linux.
The %x
format specifier requires unsigned int
value, otherwise it's undefined behaviour (so anything could happen, you can't be sure what it does on any other compiler or maybe different moon phase). According to latest C99 draft, 7.19.6.1
The fprintf function p.8, 9 (emphasis mine)
o,u,x,X
Theunsigned int
argument is converted to unsigned octal (o
), unsigned decimal (u
), or unsigned hexadecimal notation (x
orX
)If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined .
Note that for pointers you should use %p
format specifer rather than %x
or %d
, eg:
printf("%p\n", (void *) ip);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.