[英]My compiler returned "assignment to 'int *' from incompatible pointer type 'char *' [-Wincompatible-pointer-types]" when I ran my C program
#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;
}
I get this error each time I compile the code on VScode but never on code blocks.每次我在 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"
The warning tells you exactly what it is.警告会准确地告诉您它是什么。 It says:
它说:
incompatible pointer types initializing 'int *' with an expression of type 'char *'
不兼容的指针类型用“char *”类型的表达式初始化“int *”
This means that p
is of type int *
, that &grade
is of type char *
, and that these two pointers are not compatible.这意味着
p
的类型为int *
, &grade
的类型为char *
,并且这两个指针不兼容。 The solution is to change the declaration of p
to:解决方法是将
p
的声明改为:
char *p = &grade;
One more thing.还有一件事。 Usually you can safely do implicit conversions to and from any pointer to
void *
, but not when passed as argument to a variadic function.通常,您可以安全地与指向
void *
任何指针进行隐式转换,但当作为参数传递给可变参数函数时则不行。 If you want to print the address, use this:如果要打印地址,请使用以下命令:
printf("%p", (void *)p);
But only cast when needed.但只在需要时施放。 Never do it just to get rid of warnings.
永远不要仅仅为了摆脱警告而这样做。 Here is an answer I wrote about that: https://stackoverflow.com/a/62563330/6699433
这是我写的一个答案: https : //stackoverflow.com/a/62563330/6699433
As an alternative, you could use a void pointer directly:作为替代方案,您可以直接使用 void 指针:
void *p = &grade;
printf("%p", p);
But then you would need to cast if you want to dereference it.但是,如果您想取消引用它,则需要进行转换。 For example:
例如:
char c = *(char*)p;
That cast is not necessary if p
is declared as char *
.如果
p
声明为char *
则不需要该转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.