我们只是在指针上做了一个关于C的教训,我在linux机器上运行示例代码时遇到了麻烦(Mint 17 64 bit)虽然它在Windows 7(32位)上正常运行.代码如下:
#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;
}
Run Code Online (Sandbox Code Playgroud)
该程序在具有代码块ide的Windows上按预期运行,但在linux上尝试使用GCC在终端中编译时出现以下错误:
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);
^
Run Code Online (Sandbox Code Playgroud)
我想知道发生了什么以及如何让代码在linux上运行.
该%x格式说明需要unsigned int的值,否则它是未定义的行为(所以什么事情都可能发生,你不能确定它的功能上的任何其他编译器或可能不同月相).根据最新的C99草案,7.19.6.1 fprintf功能 p.8,9(强调我的)
o,u,x,X该unsigned int参数被转换为无符号八进制(o),无符号十进制(u),或无符号十六进制表示法(x或X)如果任何参数不是相应转换规范的正确类型,则行为未定义.
请注意,对于指针,您应该使用%p格式说明符而不是%x或%d,例如:
printf("%p\n", (void *) ip);
Run Code Online (Sandbox Code Playgroud)