首页 > 解决方案 > 在 C 中修改 const 指针

问题描述

我试图理解为什么以下代码可以编译并运行良好。我希望使用datainside的任何分配都f不会编译时出现 gcc 错误assignment of member ‘i’ in read-only object。是否有某种异常,因为data.i是动态分配的?

#include <stdio.h>
#include <stdlib.h>

struct a {
    int *i;
};

void f(const struct a *data) {
    data->i[0] = 55; 
}

int main() {
    struct a data;
    data.i = malloc(2 * sizeof(int));
    
    f(&data);
    
    printf("%d\n", data.i[0]);
    
    return 0;
}

标签: cpointersmallocconst-pointer

解决方案


const前面的 astruct将使其只读。如果结构包含指针成员,则这些指针本身将变为只读。不是他们所指的。

也就是说,如果它被声明为,const struct a将使成员行为,这意味着指针本身不能更改为指向其他地方。指向的数据仍然是读/写的。iint *const i;int

如果要限制对i函数内部的访问,则应使该函数接受一个const int*参数并将i成员传递给该函数。


推荐阅读