#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()
返回一個const指針?的C函數返回常量指針分配給非const指針 - 警告不是錯誤
我正在使用gcc,它只在int * p = func();
行顯示警告:「警告:初始化放棄指針目標類型的限定符」。
謝謝。
有一種方法讓編譯器顯示錯誤,而不是此警告? – printfede
@prinfede:'-pedantic-errors'或'-Werror'。 –
OP返回的內容不是一個常量指針,而是一個指向const(或只讀)對象的指針。 –