问题:分配只读成员 [英] Problem: assignment of read-only member

查看:36
本文介绍了问题:分配只读成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

/ * 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

推荐答案

gcc-4.3 -c test.c

test .c:在函数''f''中:

test.c:7:错误:只读成员'x'的分配


一旦初始化结构,我希望x是不可变的。怎么做

我初始化它?我查看了C常见问题解答,但没有看到任何特别针对此问题的



或者我可能会以错误的方式解决这个问题?


Adam
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


On Sun,2008年9月14日10:33:13 -0700,aburry写道:
On Sun, 14 Sep 2008 10:33:13 -0700, aburry wrote:

/ * 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 * /

/* 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:在函数''f''中:

test.c:7:错误:只读成员'x'的分配


我希望x在初始化结构后是不可变的。我如何
初始化它?我查看了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.



初始化动态分配结构的唯一方法是使用

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.


或许我正在以错误的方式解决这个问题?
Or perhaps I''m going about this the wrong way?



问题是没有真正理智的正确方法。你或许可以使用这个: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.


这篇关于问题:分配只读成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆