gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:08:58 24 4
gpt4 key购买 nike

我们刚刚上了一节关于指针的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com