0
#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"
4

1 回答 1

1

警告会告诉你它到底是什么。它说:

使用“char *”类型的表达式初始化“int *”的不兼容指针类型

这意味着 thatp是 type int *,that&grade是 type 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 *

于 2020-11-23T13:42:38.220 回答