首页 > 解决方案 > 堆栈帧折叠导致引用的值丢失

问题描述

我目前正在尝试将数组中的值加载到我用链表实现的堆栈数据结构中。在我的 push() 函数中,我通过使用指针在链表中创建每个新节点,这样当 push() 堆栈框架折叠并且控制返回到 reverse() 时它们不会消失。但是,即使我通过使用指针传递信息,我引用的项目似乎也没有返回,因为尽管在被调用函数中获得了有效值,但我仍然在调用函数中获得 NULL 值。为什么这些信息没有返回到我的调用函数?

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

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

void push(char x, struct Node* tp)
{
    struct Node* temp = (struct Node*)malloc(sizeof(struct Node*));
    temp->data = x;
    temp->next = tp;
    tp=temp;
    printf("\ntp points to %p", tp);
}

void reverse (char c[])
{
    struct Node* tp = NULL;
    int i = 0, j = 0;
    while (c[i] != '\0')
    {
        push(c[i], tp);
        printf("\ntp points to %p", tp);
        i++;
    }
}

int main(void)
{
    char c[] = {"coolio"};
    printf("\n%s", c);
    reverse(c);
}

标签: cpointersstructlinked-liststack

解决方案


问题是push不能改变tp你从 传递它reverse,因为它tp是按值传递的。更改函数以返回要分配给的值tp,如下所示:

struct Node* push(char x, struct Node* tp) {
    ... // your code here
    return temp;
}

调用应如下所示:

while (c[i] != '\0') {
    tp = push(c[i], tp);
    printf("\ntp points to %p", (void*)tp);
    i++;
}

请注意,使用%p需要强制转换为void*.

演示。


推荐阅读