#include <stdio.h>
int main()
{
char grade = 'A';
int *p = &grade;
printf("The address where the grade is stored: %p\n", p);
printf("Grade: %c\n", grade);
return 0;
}
每次在 VScode 上编译代码时都会出现此错误,但从未在代码块上编译。warning: incompatible pointer types initializing 'int *' with an
expression of type 'char *' [-Wincompatible-pointer-types]
int *p = &grade;
^ ~~~~~~
1 warning generated.
./main
The address where the grade is stored: 0x7ffc3bb0ee2b
Grade: A"
最佳答案
警告会告诉你它到底是什么。它说:
incompatible pointer types initializing 'int *' with an expression of type 'char *'
这意味着
p
是 int *
类型, 那 &grade
是 char *
类型,并且这两个指针不兼容。解决方法是更改p
的声明到:char *p = &grade;
还有一件事。通常你可以安全地与任何指向 void *
的指针进行隐式转换。 ,但不是作为参数传递给可变参数函数时。如果要打印地址,请使用以下命令:printf("%p", (void *)p);
但只在需要时施放。永远不要仅仅为了摆脱警告而这样做。这是我写的一个答案:https://stackoverflow.com/a/62563330/6699433作为替代方案,您可以直接使用 void 指针:
void *p = &grade;
printf("%p", p);
但是,如果您想取消引用它,则需要强制转换。例如:char c = *(char*)p;
如果 p
则不需要该类型转换。声明为 char *
.
关于c - 当我运行 C 程序时,我的编译器返回 "assignment to ' int *' from incompatible pointer type ' char *' [-Wincompatible-pointer-types]",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64969194/