问题描述
/ * test.c * /
#include< stdlib.h>
void f(){
struct X {const int x; };
struct X * myx = malloc(sizeof(struct X));
myx-> x = 42;
}
/ * test of test.c * /
$ gcc-4.3 -c test.c
test.c:In函数''f'':
test.c:7:错误:只读成员'x'的分配
我想x一旦struct初始化,它就是不可变的。怎么做
我初始化它?我查看了C常见问题解答,但没有看到任何特别针对此问题的
。
或者我可能会以错误的方式解决这个问题?
Adam
/* test.c */
#include <stdlib.h>
void f() {
struct X { const int x; };
struct X* myx = malloc(sizeof(struct X));
myx->x = 42;
}
/* end of test.c */
$ gcc-4.3 -c test.c
test.c: In function ''f'':
test.c:7: error: assignment of read-only member ''x''
I would like x to be immutable once the struct is initialized. How do
I initialize it? I looked in the C FAQ but did not see anything that
addressed this specifically.
Or perhaps I''m going about this the wrong way?
Adam
推荐答案
初始化动态分配结构的唯一方法是使用
calloc,如果你这样做,你就不能选择初始化值。
The only way to initialise a dynamically allocated structure is by using
calloc, and if you do that, you can''t choose an initialiser value.
问题是没有真正理智的正确方法。你或许可以使用这个:b
$ b struct X {const int x; };
struct X * myx = malloc(sizeof * myx);
struct X myx_value = {42};
memcpy(myx, & myx_value,sizeof * myx);
但它很难看。
The problem is that there is not really a sane right way. You may be able
to use this:
struct X { const int x; };
struct X *myx = malloc(sizeof *myx);
struct X myx_value = { 42 };
memcpy(myx, &myx_value, sizeof *myx);
but it''s ugly.
这篇关于问题:分配只读成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!