c - 堆栈帧折叠导致引用的值丢失
问题描述
我目前正在尝试将数组中的值加载到我用链表实现的堆栈数据结构中。在我的 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
不能改变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*
.
推荐阅读
- hadoop - 如何导入。使用 sqoop 将 dat 文件放入 mysql 表中,但它给出空值
- awk - 使用 grep/sed/awk 命令读取 pwd 生成的最后一个值
- c# - 当数据集WriteXml()函数生成xml文件时,C#如何使用XDocument类更新xml文件
- python - 如何从数组中查找不包含某些数字的数字?
- node.js - 如何结合两个功能
- sql - SQL Server Maths 函数在声明的变量/实际值之间有什么不同?
- laravel - Laravel 过滤与 whereIn 数组值的多对多关系
- python - 可以在 Python 中更快地进行这种 inpaint 插值吗?
- ios - Cordova HttpClient IOS 失败响应
- python - Theano AttributeError: 'TensorVariable' 对象没有属性 'rank'