[英]Various ways of accessing nested structure member
typedef struct struct1 {
struct struct2 id2;
};
typedef struct struct2{
int a;
};
int fn( struct struct1 *id1)
{
id1->id2->a=4;
return 1;
}
Error : fn
technique it was showing error : error C2232: '->a'
: left operand has 'struct' type, use '.'
错误: fn
技术显示错误:错误C2232: '->a'
:左操作数为'struct'类型,使用'.'
Solution1 :Help of error message 解决方案1:错误消息的帮助
int fn1( struct struct1 *id1)
{
id1->id2.a=4;
return 1;
}
OR 要么
Solution 2: By using struct2
pointer 解决方案2:通过使用struct2
指针
int fn2( struct struct1 *id1)
{
struct struct2 *id2 = &id1->id2;
id2->a=4;
return 1;
}
The second method fn2
technique is also valid . fn2
技术的第二种方法也是有效的。
What are the other possible solutions to access the struct2
member . 访问struct2
成员还有哪些其他可能的解决方案。
I want to know about this concept in depth . 我想深入了解这个概念。 Knowledge me on this . 了解这一点。
There are not too many ways. 没有太多的方法。 One "other" way is to use void *
: 一种“其他”方式是使用void *
:
int fn2( void *id1) // Called with a 'struct struct1*'
{
struct struct1 *p = id1;
void *p2 = p->id2;
((struct struct2*)p2)->a=4;
return 1;
}
But this is not really a different way. 但这并不是真的不同。 In fact, the two methods you have and this one are all fundamentally the same. 实际上,您拥有的这两种方法和该方法基本上都相同。
The only difference is that ->
is used to to access members of a pointer to struct where .
唯一的区别是->
用于访问指向 struct where的指针的成员.
is used to to access members of a struct. 用于访问结构的成员。
You can use the .
您可以使用.
to access members and avoid ->
altogether: 访问成员并避免->
完全:
int fn( struct struct1 *id1)
{
(*id1).id2.a=4;
return 1;
}
or 要么
int fn2( struct struct1 *id1)
{
struct struct2 id2 = (*id1).id2;
id2.a=4;
return 1;
}
The ->
operator is just a convenience to access members of a struct
pointer than anything else. ->
运算符是访问struct
指针成员的一种便利,而不是其他任何便利。
There are two ways to access a member of a structure. 有两种访问结构成员的方法。 Either using a pointer to the structure or the structure itself: 使用指向结构的指针或结构本身:
struct S {
int m;
};
struct S s;
struct S *ps = s;
s.m; // direct access through structure
ps->m; // access through pointer to structure
(*ps).m; // direct access of the structure through dereferencing the pointer
(&s)->m; // get address of structure and get member through it
Then for your example you can write many different things, as: 然后以您的示例为例,您可以编写许多不同的内容,例如:
id1->id2.a=4;
(*id1).id2.a=4;
(&(id1->id2))->a = 4;
(&((*id1).id2))->a = 4;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.