skanda93
skanda93

Reputation: 195

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 '.'

Solution1 :Help of error message

 int fn1( struct struct1 *id1)
{

    id1->id2.a=4;
     return 1;
}

OR

Solution 2: By using struct2 pointer

int fn2( struct struct1 *id1) 
{
    struct struct2 *id2 = &id1->id2;
    id2->a=4;
     return 1;
}

The second method fn2 technique is also valid .

What are the other possible solutions to access the struct2 member .

I want to know about this concept in depth . Knowledge me on this .

Upvotes: 1

Views: 222

Answers (2)

Jean-Baptiste Yunès
Jean-Baptiste Yunès

Reputation: 36401

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;

Upvotes: 1

P.P
P.P

Reputation: 121397

There are not too many ways. One "other" way is to use 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 . 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.

Upvotes: 1

Related Questions