1

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;
}
pavikirthi
  • 1,569
  • 3
  • 17
  • 26
  • 3
    Don't use double-underscore prefix, those are reserved for the implementation. https://stackoverflow.com/questions/1449181/what-does-double-underscore-const-mean-in-c?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Barmar May 29 '18 at 18:40
  • 2
    Not really sure what you are trying to do here, but `acc` is uninitialized. – Christian Gibbons May 29 '18 at 18:40
  • @ChristianGibbons I think his question may be what he's supposed to set it to. – Barmar May 29 '18 at 18:41
  • 2
    Use pointers rather than embedding copies of structs within structs. – jwdonahue May 29 '18 at 18:42
  • @Barmar, that's right, what should I do so that if one changes other should also reflect the same changes with respect to val1 and val2 – pavikirthi May 29 '18 at 18:42

1 Answers1

3

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);
Barmar
  • 741,623
  • 53
  • 500
  • 612