簡體   English   中英

struct指針內部的結構指針

[英]Reference struct pointer inside struct pointer

抱歉,這個問題這個問題非常相似,但我有一個大腦屁時刻,我正在尋找良好和正確的方法來做到這一點。

我正在啟動一個新的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?

    //...

}

要添加到另一個類似的問題的參考(我總是發布找到他們)有一個類似的問題, 這里有一個同樣簡單的答案。

是的 - 你在thing_struct中訪問成員“a”的方式是正確的。

但是 - 出於我的想法 - 你應該將param的地址傳遞給phtread_create(...)。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM