pavikirthi
pavikirthi

Reputation: 1655

reflect changes to both struct if changes are made to only one struct

I have the following structs where access2 uses ctx1 indirectly through access1. Suppose if I set the value of val1 through access2, how can I make sure that access1 also reflects the same changes as shown in main()?

typedef struct __ctx1{
   int val1;
   int val2;
}ctx1;

typedef struct __access1{
   int counts;
   ctx1 cx1;
}access1;

typedef struct __access2{
  int options;
  access1 base1;
}access2;


int main(){
 access2 *base2;
 base2->base1.cx1.val1 = 5;
 access1 *acc;
 printf("val1 %d\n",acc->cx1.val1);
 return 0;
}

Upvotes: 1

Views: 43

Answers (1)

Barmar
Barmar

Reputation: 782025

Set acc to point to the address of that substructure:

access1 *acc = &(base2->base1);

You also never allocated space for base2 to point to, it should be:

access2 *base2 = malloc(sizeof access2);

Upvotes: 3

Related Questions