2011-05-25 156 views
2

對不起,這個愚蠢的標題。設置結構的指針成員,從指針指向結構的指針

對於(非常基本的)任務的一部分,我們正在實現一個帶指針的堆棧。我在一小部分時遇到了很多麻煩,所以我將它分解成了這個小問題。

我會盡力解釋我的問題,但閱讀代碼可能會更容易理解。

有一個結構(名爲節點),它具有2個成員,一個char(名爲data)和一個指向另一個節點(名爲next)的指針。

在main函數裏我有一個名爲head的指向node1的指針,我想把這個指針傳遞給另一個函數,並使它指向一個新節點(並且使這個新節點指向另一個新節點) 。我想我可能會將指針設置爲新節點,但我無法正確地將該新節點正確指向另一個新節點。

#include <stdio.h> 

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

void modifyPtr(struct node **p); 

int main(void) 
{ 
    /* create first 2 nodes */ 
    struct node n1; 
    n1.data = '1'; 

    struct node n2; 
    n2.data = '2'; 

    /* set 1st node's next node to the 2nd node */ 
    n1.next = &n2; 

    /* create a pointer to a node and make it point to the first node */ 
    struct node *head = &n1; 

    /* this works as expected */ 
    printf("1. %c\n", head->data); 
    printf("2. %c\n", head->next->data); 

    /* this should set head to a new node (which in turn points to another new node) */ 
    modifyPtr(&head); 

    /* this prints as expected. Am I just lucky here? */ 
    printf("3. %c\n", head->data); 
    /* but this doesn't. I want it to print 4. */ 
    printf("4. %c\n", head->next->data); 
} 

void modifyPtr(struct node **p) 
{ 
    /* create node 3 and 4 */ 
    struct node n3; 
    n3.data = '3'; 

    struct node n4; 
    n4.data = '4'; 

    /* set node3's next node to node4 */ 
    n3.next = &n4; 

    /* make p point to node 3 */ 
    *p = &n3; 
} 

我希望看到的輸出

而是我得到

  1. |

我一直在努力讓它工作多年。我在想,也許這是爲了在modifyPtr的本地範圍內創建節點並嘗試在main中使用它們。但是我不明白爲什麼#3會起作用。

有人能告訴我我做錯了什麼嗎?謝謝。

回答

5
void modifyPtr(struct node **p) 
{ 
    struct node n3; 
    n3.data = '3'; 
    ... 
    *p = &n3; 
} 

n3n4是局部變量*,所以他們不再modifyPtr回報存在一次。你需要在堆上分配它們。

void modifyPtr(struct node **p) 
{ 
    struct node *pn3 = malloc(sizeof(struct node)); 
    pn3->data = '3'; 
    ... 
    *p = pn3; 
} 

你只是幸運n3.data沒有得到破壞。

* — Laymen說。

+0

非常感謝!我不能將此設置爲接受的答案,但我很快就會。 – Ants 2011-05-25 03:24:26

3

你對這個範圍感興趣。解釋#3的方法是,僅僅因爲它的作用並不意味着它總是會的,並不意味着它是正確的。學習動態內存分配的時間:new/delete或malloc/free

+0

謝謝克里斯。在我寫這個問題的時候,範圍的東西只是一個過去的想法。 ikegami在你之前回答,所以我會讓答案接受答案,但謝謝。 – Ants 2011-05-25 03:23:11

+0

感謝螞蟻的友善之詞。 – Chris 2011-05-25 03:33:08