Search code examples
cstructlvalue

structure in c whose members are also structures


I have following structs:

typedef struct stack {
    void* ss_sp;
    size_t ss_size;
    // ...
} stack_t; 

typedef struct ucontext {
    ucontext_t* uc_link;
    stack_t uc_stack;
    // ...
} ucontext_t;

typedef struct mythread_type {
    ucontext_t context;
    int ID;
    int status;
} mythread_t; 

Now I have an array as follows:

mythread_t mythreads[100];

I want to avoid using

mythreads[0].context.uc_stack.ss_size 

for readability reason.

Now I was wondering if the following two blocks of code are equivalent:

  • block 1

    ucontext_t c=mythreads[0].context;
    getcontext(&c);
    c.uc_stack.ss_size=1024;
    c.uc_stack.ss_sp=malloc(1024);
    
  • block 2

    ucontext_t* c=&(mythreads[0].context);
    getcontext(c);
    (c->uc_stack).ss_size=1024;
    (c->uc_stack).ss_sp=malloc(1024);
    

What I want is the context of the mythreads[0] stack to allocate 1024 bytes.


Solution

  • The following is copy of mythreads[0].context:

    ucontext_t c = mythreads[0].context;
    

    In opposite the following is pointer to mythreads[0] context

    ucontext_t* c = &(mythreads[0].context);
    

    As a result the first peace of code makes modification of the copy (it does not enfluence on the mythreads[0] context), the second one modifies the mythreads[0] context.