#include <stdio.h>
#include <stdlib.h>
const int * func()
{
int * i = malloc(sizeof(int));
(*i) = 5; // initialize the value of the memory area
return i;
}
int main()
{
int * p = func();
printf("%d\n", (*p));
(*p) = 3; // attempt to change the memory area - compiles fine
printf("%d\n", (*p));
free(p);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为什么(*p)即使func()返回 const 指针,编译器也允许我进行更改?
我正在使用 gcc,它只显示一条警告int * p = func();:“警告:初始化丢弃来自指针目标类型的限定符”。
谢谢。