简体   繁体   English

struct指针内部的结构指针

[英]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. 我正在启动一个新的pthread来处理一些数据,这意味着我们只能传递一个指针,在这种情况下,因为我们想要将几个东西传递给线程,指针指向一个结构。

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. 是的 - 你在thing_struct中访问成员“a”的方式是正确的。

But - out of my head - you should pass the address of param to phtread_create(...). 但是 - 出于我的想法 - 你应该将param的地址传递给phtread_create(...)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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