2013-03-01 163 views
0

我试图为主列表中的每个元素创建一个小列表。我有主列表工作正常,但我不知道如何访问和添加元素到小列表中。将元素添加到链接列表中的链接列表中C

struct smallList 
{ 
    char data; 
    struct smallList *next; 
}; 

struct bigList 
{ 
    char data; 
    struct bigList *next; 
    struct smallList *head; 
} *root; 

当我添加的东西向主列表,我宣布为每个新节点:

newNode->head = NULL; 

我用这个功能将当前指针到达主列表中的元素:

struct bigList *pointer = getPointer(root, value); 

然后,添加东西到它的smallList| using that pointer. I pass along pointer-> head`到这个函数。它不工作。

insert(pointer->head, value) 
+0

了解如何传递*指针by-address *(即指向指针的指针)。 – WhozCraig 2013-03-01 02:50:49

回答

0

正如WhozCraig所示,您可以使用指向指针的指针来解决您的问题。事情是这样的:

void insert(struct smallList **head, char value) 
{ 
    *head = newSmallList(value, *head); 
} 

newSmallList会是这样的:

struct smallList *newSmallList(char value, struct smallList *rest) 
{ 
    struct smallList *result = malloc(sizeof(struct smallList)); 
    result->next = rest; 
    result->data = value; 
    return result; 
} 

与当前设置的问题是,你正在过值的指针 - >头场的(这恰好当你想要改变存储在该字段中的内容时,该函数将被调用。下面是一个使用整数表示类似错误的程序:

void setFive(int i) 
{ 
    i = 5; 
} 

int main(void) 
{ 
    int myInt = 7; 
    setFive(myInt); 
    printf("%d\n", myInt); /* still 7! */ 
    return 0; 
}