【问题标题】:referenced values are lost with stack frame collapse堆栈帧折叠导致引用的值丢失
【发布时间】:2018-11-26 06:14:23
【问题描述】:

我目前正在尝试将数组中的值加载到我使用链表实现的堆栈数据结构中。在我的 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);
}

【问题讨论】:

  • 您正在按值传递指针。它不会在 reverse 方法中更新 tp 变量。

标签: c pointers struct linked-list stack


【解决方案1】:

问题是push 不能改变你从reverse 传递的tp,因为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*

Demo.

【讨论】:

    猜你喜欢
    • 2011-07-02
    • 1970-01-01
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-19
    • 1970-01-01
    • 2015-08-24
    相关资源
    最近更新 更多