c - 当我运行 C 程序时,我的编译器返回 "assignment to ' int *' from incompatible pointer type ' char *' [-Wincompatible-pointer-types]"

标签 c compiler-errors clang compiler-warnings gcc-warning

#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 *'


这意味着 pint * 类型, 那 &gradechar * 类型,并且这两个指针不兼容。解决方法是更改​​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/

相关文章:

xamarin - 编译Xamarin Forms新项目时出错

c++ - Windows10 上的 LLD 链接错误 : no input files when trying to link with libcmt. lib

clang - 如何在 Clang 中以字符串形式获取函数定义/签名?

Clang:在哪里定义了 -Wall 选项?

c - "Warning: Linking the shared library against static library is not portable"是什么意思?

c - 尝试加密和解密 code-beginner

c - 如何删除数组中的结束用户输入值?

java - 允许在 DVD+R 上编译 DVD+R 上的 java 程序

c - 结构体数组错误

c++ - 尝试编译我的wxWidgets程序时出现 “is_enum not declared in this scope”错误