【发布时间】:2011-10-12 01:08:24
【问题描述】:
#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;
}
为什么编译器允许我更改(*p),即使func() 返回一个常量指针?
我正在使用 gcc,它只在 int * p = func(); 行显示警告:“警告:初始化丢弃来自指针目标类型的限定符”。
谢谢。
【问题讨论】:
-
有办法让编译器显示错误而不是这个警告吗?
-
@prinfede:
-pedantic-errors或-Werror。 -
OP 返回的不是 const 指针,而是指向 const(或只读)对象的指针。
标签: c function pointers return-type