简体   繁体   中英

Reference struct pointer inside struct pointer

Apologies for this being so similar to this question but I'm having one of those brain-fart moments and am looking for the Good And Right way to do this.

I am launching a new pthread to handle some data, which means we can only pass a pointer, in this case because we want to pass several things to the thread the pointer is to a struct.

That data struct itself contains a pointer to another data structure.

So, given this setup, what is the correct way to populate & access the nested struct?

struct things_struct
{
    int a;
    int b;
};

struct thread_params
{
    int flag;
    struct things_struct *things;
}

int main()
{
    struct thread_params params;
    struct things_struct the_things;

    params.things = &the_things;

    // Launch thread
    pthread_create(&thrptr, NULL, PrintThings, (void *)params);

    //...

}

// The thread
void *PrintThings(void *arg)
{
    struct thread_params *params = (thread_params *)arg; // cast back to correct type

    int local_a = params->things->a; // is this correct?

    //...

}

To add a reference to another similar question (I always find them after posting) there's a similar question here with a similarly simple answer.

Yes - your way to access member "a" in things_struct is correct.

But - out of my head - you should pass the address of param to phtread_create(...).

pthread_create(&thrptr, NULL, PrintThings, (void *)&params);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM