c - 为什么我的 printf 格式不适用于 GCC 但在 Windows 上运行

标签 c linux gcc

我们刚刚上了一节关于指针的 C 课,我在我的 linux 机器(Mint 17 64 位)上运行示例代码时遇到了问题,尽管它在 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;
}

程序在带有代码块的 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);
  ^

我想知道发生了什么以及如何让代码在 linux 上运行。

最佳答案

%x 格式说明符需要 unsigned int 值,否则它是未定义的行为(因此任何事情都可能发生,您无法确定它在任何其他编译器上的作用或者可能是不同的月相)。根据最新的 C99 草案,7.19.6.1 fprintf 函数 p.8, 9(强调我的)

o,u,x,X The unsigned int argument is converted to unsigned octal (o), unsigned decimal (u), or unsigned hexadecimal notation (x or X)

If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

请注意,对于指针,您应该使用 %p 格式说明符而不是 %x%d,例如:

printf("%p\n", (void *) ip);

关于c - 为什么我的 printf 格式不适用于 GCC 但在 Windows 上运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24848331/

相关文章:

python - 如何返回 Flex 中 token 的最短匹配?

gcc - gcc 是否有计算 “lines of code compiled” 的工具或编译器选项?

c++ - 可以在 C++ 中以可移植的方式使用命名属性初始化 POD 结构吗?

linux - 尽管有 sudo 权限,但编译 Clozure CL 时出现权限错误

linux - git: Linux-Next,如何将 linux-next 重置为特定日期?

c - Windows 7 7 上的 Tiny C 编译器

c - 在 C 中修改函数中的变量

c++ - 运算符优先顺序和求值困惑

检查是否定义了多行宏

c - 如果 open() 系统调用未能完成,我们是否需要调用 close() ?