小编pri*_*ede的帖子

C 函数返回分配给非常量指针的常量指针 - 警告不是错误

#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 pointers function return-type

2
推荐指数
1
解决办法
1万
查看次数

标签 统计

c ×1

function ×1

pointers ×1

return-type ×1