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

问题描述

| 对不起,这个愚蠢的标题。 对于(非常基本的)分配的一部分,我们正在实现带有指针的堆栈。我一小部分遇到了很多麻烦,因此我将其隔离为一个小问题。 我将尝试解释我的问题,但是阅读代码可能更容易理解。 有一个结构(命名节点),该结构具有2个成员,一个char(命名数据)和一个指向另一个节点(下一个命名)的指针。 在主函数中,我有一个名为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个 2 3 4 但是我得到了 1个 2 3 | 我一直在努力使它工作已经很久了。我认为这可能与在ModifyPtr本地范围内创建节点并尝试在main中使用它们有关。但是后来我不明白为什么#3会起作用。 有人可以告诉我我在做什么错吗?谢谢。     

解决方法

void modifyPtr(struct node **p)
{
    struct node n3;
    n3.data = \'3\';
    ...
    *p = &n3;
}
n3
n4
是局部变量*,因此一旦
modifyPtr
返回,它们就不再存在。您需要在堆上分配它们。
void modifyPtr(struct node **p)
{
    struct node *pn3 = malloc(sizeof(struct node));
    pn3->data = \'3\';
    ...
    *p = pn3;
}
你真幸运,
n3.data
没有被破坏。 *-外行讲话。     ,您对范围有所了解。解释#3的方法是,仅仅因为它起作用并不意味着它总是会,也不意味着它是对的。学习动态内存分配的时间:新/删除或malloc /免费