【发布时间】:2020-09-28 06:10:24
【问题描述】:
我有一个点结构:
struct Point
{
const int x;
const int y;
};
在我的代码中,我有很多这样的点,所以我想创建指向它们的指针,这样我在处理它们时就不会看到它们被一遍又一遍地复制。
知道您可以像这样初始化结构的常量成员:
struct Point my_point = { .x = 1, .y = 2};
我认为我可以对动态分配的结构做同样的事情。但似乎并非如此:
struct Point *point = malloc(sizeof(struct Point));
*point = (struct Point){.x = 1, .y = 2};
但是我得到了
main.c: In function ‘main’:
main.c:23:8: error: assignment of read-only location ‘*point’
*point = (struct Point){.x = 1, .y = 2};
使用 GCC 7.1.1 时。在铿锵声中,我得到了
prog.c:23:8: error: cannot assign to lvalue with const-qualified data member 'x'
*point = (struct Point){.x = 1, .y = 2};
~~~~~~ ^
prog.c:14:15: note: data member 'x' declared const here
const int x;
~~~~~~~~~~^
prog.c:15:15: note: data member 'y' declared const here
const int y;
~~~~~~~~~~^
1 error generated.
有没有办法做到这一点?
例子
#include <stdio.h>
#include <stdlib.h>
struct Point
{
const int x;
const int y;
};
int main()
{
struct Point *point = malloc(sizeof(struct Point));
*point = (struct Point){.x = 1, .y = 2};
return 0;
}
【问题讨论】:
-
为什么
x和y需要只读? -
@JHBonarius 只是方便。我想向查看它的人发出信号,这些值预计不会更改(它们是从文件中加载的,因此无论如何在我的应用程序中更改它们是没有意义的)。