3

我试图理解为什么以下代码可以编译并运行良好。我希望使用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;
}
4

3 回答 3

2

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

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

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

于 2020-08-20T10:20:32.980 回答
1

在下面的代码中,const表示data不修改指向的内容。 data->i[0] = 55;不修改指针data->i。相反,那行代码修改了 . 指向的内存data->i。这是允许的,因为指针.iisint *而不是const int *

struct a {
    int *i;
};

void f(const struct a *data) {
    data->i[0] = 55; 
}
于 2020-08-20T09:53:59.863 回答
0

You cant modify i but you can modify the objects referenced by i.

To prevent it you need to:

struct a {
    const int *i;
};
于 2020-08-20T10:27:01.590 回答