设置结构的指针成员,从指针指向结构的指针

问题描述:

对不起,这个愚蠢的标题。设置结构的指针成员,从指针指向结构的指针

对于(非常基本的)任务的一部分,我们正在实现一个带指针的堆栈。我在一小部分时遇到了很多麻烦,所以我将它分解成了这个小问题。

我会尽力解释我的问题,但阅读代码可能会更容易理解。

有一个结构(名为节点),它具有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会起作用。

    有人能告诉我我做错了什么吗?谢谢。

    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的方法是,仅仅因为它的作用并不意味着它总是会的,并不意味着它是正确的。学习动态内存分配的时间:new/delete或malloc/free

    +0

    谢谢克里斯。在我写这个问题的时候,范围的东西只是一个过去的想法。 ikegami在你之前回答,所以我会让答案接受答案,但谢谢。 – Ants 2011-05-25 03:23:11

    +0

    感谢蚂蚁的友善之词。 – Chris 2011-05-25 03:33:08