我目前正在尝试将数组中的值加载到我用链表实现的堆栈数据结构中。在我的 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);
}
最佳答案
问题是 push
不能改变你从 reverse
传递的 tp
,因为 tp
被传递了按值(value)。更改函数以返回要分配给 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*
。
关于c - 堆栈框架崩溃时引用的值丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50891854/