【发布时间】: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