C语言指针代码编译错误求助:按书籍编写仍无法编译
问题:C语言指针地址输出导致编译错误
问题代码
#include <stdio.h> int var = 1; int *ptr; int main(void) { ptr = &var; printf("Var = %d", var); printf("Var = %d", *ptr); printf("The adress of the variable = %d", &var); printf("The adress = %d", ptr); return 0; }
编译错误信息
ø.c:13:47: error: format specifies type 'int' but the argument has
type 'int *' [-Werror,-Wformat]
printf("The adress of the variable = %d", &var);
~~ ^~~~
ø.c:14:31: error: format specifies type 'int' but the argument has type 'int *'
[-Werror,-Wformat]
printf("The adress = %d", ptr);
~~ ^~~
问题核心
错误原因是printf格式化符与指针地址类型不匹配:%d用于输出int类型数据,但&var(变量var的地址)和ptr(指向var的指针)都是int*类型,直接用%d输出会触发类型不兼容的编译错误。
解决方法
输出指针地址必须使用%p格式化符,且需要将指针强制转换为void*类型(这是%p的标准要求)。同时修正拼写错误并添加换行符优化输出格式,修改后的代码如下:
#include <stdio.h> int var = 1; int *ptr; int main(void) { ptr = &var; printf("Var = %d\n", var); printf("Var = %d\n", *ptr); printf("The address of the variable = %p\n", (void*)&var); printf("The address = %p\n", (void*)ptr); return 0; }
内容的提问来源于stack exchange,提问作者Alona Chaika
相关产品推荐
相关产品推荐

