struct指针内部的结构指针

时间:2014-04-09 12:17:52

标签: c pointers struct nested

抱歉这与this question非常相似,但我有一个大脑屁时刻,我正在寻找 Good And Right 方式来做到这一点。

我正在启动一个新的pthread来处理一些数据,这意味着我们只能传递一个指针,在这种情况下,因为我们想要将几个东西传递给线程,指针指向一个结构。

该数据结构本身包含指向另一个数据结构的指针。

所以,鉴于这种设置,填充和放置的正确方法是什么?访问嵌套结构?

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?

    //...

}

要添加对其他类似问题的引用(我总是在发布后找到它们),会有一个类似的问题here,答案也很简单。

1 个答案:

答案 0 :(得分:2)

是的 - 您访问会员的方式" a"在things_struct中是正确的。

但是 - 出于我的想法 - 你应该将param的地址传递给phtread_create(...)。

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