[英]Assign struct to multiple structure member
I would like to initialize several members of a structure by assigning a "matching" structure to the members without explicitly assigning each member.我想通过为成员分配“匹配”结构而不显式分配每个成员来初始化结构的多个成员。
Here is an example to better explain it.这是一个更好地解释它的例子。 I have two structures:
我有两个结构:
typedef struct
{
void* ThingB;
void* ThingC;
}SomeThings_S;
typedef struct
{
void* ThingA;
void* ThingB;
void* ThingC;
}AllThings_S;
I would like initialize members ThingB and ThingC in AllThings_S by directly assigning Somethings_S to members ThingB and ThingC in AllThings_S.我想通过直接将Somethings_S分配给AllThings_S中的成员ThingB和ThingC来初始化AllThings_S中的成员ThingB和ThingC。 See the following:
请参阅以下内容:
void* ThingA;
void* ThingB;
void* ThingC;
SomeThings_S SomeThings =
{
ThingB,
ThingC,
};
AllThings_S AllThings =
{
.ThingA = ThingA,
SomeThings, <--- This is where I'm not sure how to proceed.
}
I can do the following:我可以执行以下操作:
AllThings_S AllThings =
{
.ThingA = ThingA,
.ThingB = SomeThings.ThingB,
.ThingC = SomeThings.ThingC,
}
But this is what I'd like to avoid.但这是我想避免的。 I'd prefer if I can directly assign Somethings to ThingB and ThingC in AllThings.
如果我可以直接将Somethings分配给AllThings中的ThingB和ThingC,我会更喜欢。
Sorry.对不起。 I had a hard time to trying and explain.
我很难尝试和解释。 Hope it is readable.
希望它是可读的。
If you really want to do this--and I want to stress that I really don't advise this--you can make use of the -fplan9-extensions
or -fms-extensions
option in gcc that allows you to access members of anonymous structs directly.如果你真的想这样做——我想强调我真的不建议这样做——你可以使用 gcc 中的
-fplan9-extensions
或-fms-extensions
选项,它允许你访问匿名成员直接构造。 If using clang, use -fms-extensions
as it does not have the plan9 extensions last I knew.如果使用 clang,请使用
-fms-extensions
,因为它没有我上次知道的 plan9 扩展。
What it may look like:它可能是什么样子:
#include <stdlib.h>
#include <stdio.h>
typedef struct
{
void* ThingB;
void* ThingC;
}SomeThings_S;
typedef struct
{
void* ThingA;
SomeThings_S;
}AllThings_S;
int main(void) {
int a;
int b;
int c;
SomeThings_S x = {&a,&b};
AllThings_S y = {&c, x};
printf("%p, %p, %p\n", y.ThingA, y.ThingB, y.ThingC);
return EXIT_SUCCESS;
}
I solved this with the comment from EOF by using an anonymous union and structure.我通过使用匿名联合和结构从 EOF 的评论中解决了这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.