2016-04-23 143 views
0

我的問題是如何訪問列表結構的節點結構中的num變量?我嘗試了兩種方法,他們都沒有工作?我只是好奇爲什麼那樣。感謝任何幫助我的人,我知道這是一個新手問題。我相當新的C和堆棧溢出,希望我可以從這個網站學到很多東西。c中嵌套的結構體/鏈接列表

#include<stdio.h> 
#include<stdlib.h> 

typedef struct node 
{ 
    int num; 
    struct node *next; 
} node; 

typedef struct list 
{ 
    node *ptr; 
    struct list *next; 
} list; 

int main() 
{ 
    list *p = malloc(sizeof(list)); 
    //p->ptr->num = 5; 

    node *x; 
    x = p->ptr; 
    //x->num = 5; 

    return 0; 
} 
+2

列表不包含任何指向節點的指針,直到您添加它們。你需要爲'x'指定一個'node'指向,然後設置'p'指向該節點。只有這樣你才能開始訪問該值。所以,'p-> ptr = x;'比反向賦值更合理,但你仍然需要連接所有的點。 –

回答

1

是你所試圖做的是正確的,但問題是,雖然你已經爲list分配的內存,沒有分配內存駐留內listnode

list *p = malloc(sizeof(list)); 
    //p->ptr->num = 5; 
    node *x; 
    p->ptr = malloc(sizeof(node)); 
    x = p->ptr; 
    x->num = 5;