pri*_*ede 2 c pointers function return-type
#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();:“警告:初始化丢弃来自指针目标类型的限定符”。
谢谢。
您的程序无效。C 禁止隐式删除const类似的东西,并且按照规范 GCC 应该至少给你一个关于该代码的警告。你需要一个演员来删除const.
已经为此消耗了警告,但是您可以依靠程序来工作(尽管从标准的角度来看不再是这样),因为指针指向 malloc 的内存区域。并且您可以写入该区域。一个const T*指向一些内存并不意味着内存此后标记不变。
请注意,标准不要求编译器拒绝任何程序。该标准仅要求编译器有时向用户发出消息。无论是错误消息还是警告,以及消息的发出方式以及发出后发生的任何事情,标准都没有规定。