c - 在 C 中修改 const 指针
问题描述
我试图理解为什么以下代码可以编译并运行良好。我希望使用data
inside的任何分配都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;
}
解决方案
const
前面的 astruct
将使其只读。如果结构包含指针成员,则这些指针本身将变为只读。不是他们所指的。
也就是说,如果它被声明为,const struct a
将使成员行为,这意味着指针本身不能更改为指向其他地方。指向的数据仍然是读/写的。i
int *const i;
int
如果要限制对i
函数内部的访问,则应使该函数接受一个const int*
参数并将i
成员传递给该函数。
推荐阅读
- php - WordPress:防止内容字段在保存时保存
- python - 了解最大流量问题的 Python 代码
- python - 提取熊猫列中两个标记之间的文本
- google-apps-script - 当 Google 文档被锁定时,有没有办法防止插件菜单被隐藏?
- python - 表单不呈现 html 元素,只是将表单字段对象打印为文本
- python - 如何在数据框中打开嵌套的 json 或列表?
- python - json 与 kivy 在 Ubuntu 上工作但不在 android 上(Buildozer)
- ios - 使用通知推送器发送推送通知 IOS 不起作用
- c# - 如何将嵌套的 LINQ 查询转换为矩形数组?
- python - 难以理解 Qt 文档