在c中不使用成员名称为结构成员赋值?
我有一个结构,我想做的是使用 for 循环为其成员赋值。这样我就不必使用成员的名字。因为结构很长,我不需要 20 行 p_struct->member_name
等。到目前为止,我所拥有的如下,但我不确定我是否朝着正确的方向前进。< br> 在头文件中:
typedef struct {
int x;
char ch;
...
...
}data;
data g_data;
在.c文件中...
data *p_data;
p_data = &(g_data.x)
for(i=0 till struct_elements) {
*p_data = (some value);
p_data++; //next member
}
I have a structure and what I would like to do is to assign values to its members using a for loop. That way I do not have to use the members name. Because the structure is long and i do not want 20 lines of p_struct->member_name
etc. What I have so far is below, but i am not sure if i am going in the right direction.
In header file:
typedef struct {
int x;
char ch;
...
...
}data;
data g_data;
in .c file...
data *p_data;
p_data = &(g_data.x)
for(i=0 till struct_elements) {
*p_data = (some value);
p_data++; //next member
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这不是有效的 C。但是有效的 C 是创建每个成员的类型和偏移量的常量表,并在循环中使用它:
然后您可以将成员
x
作为*(int *)((char *)foo + mystruct_def[0].offset)
。这只是一个例子;现实世界的用法可能会更复杂一些......
This is not valid C. But what would be valid C is to make constant table of the types and offsets of each member, and use that in your loop:
Then you could access the member
x
as*(int *)((char *)foo + mystruct_def[0].offset)
.This is just an example; real world usage would probably be a bit more elaborate...
你不是,p_data是一个指向数据的指针,p_data++会将其向上移动sizeof(data)字节,这不会是下一个成员,而是在你的结构之外。另外,由于成员的类型不同,因此即使该问题得到解决,该方法也将不起作用。
You're not, p_data is a pointer to data, p_data++ will move it sizeof (data) bytes up, which will not be the next member, but outside your structure. Also, since members are of different types, the method will not work even if that problem would have been fixed.
如果您只是想解决一个可读性问题,那么您应该考虑使用结构体初始值设定项:
如果您使用的是 gcc(或 C99 编译器,感谢 Dietrich Epp 的提醒),那么您甚至可以编写:
If it's only a readability problem that you are trying to solve, then you should consider using a struct initializer:
If you are using gcc (or a C99 compiler, thank's Dietrich Epp for the reminder), then you can even write: