c - C - 如何更改函数外部的指针?
问题描述
我正在自己研究 C 中的数据结构,我正在尝试实现一个链表,但我不明白如何在添加新值时更改起始指针。这是我的实际代码:
#include <stdlib.h>
typedef struct node {
int value;
struct node *next;
};
struct node *transverse_list(struct node *start) {
struct node *current_node;
struct node *last;
current_node -> next = start;
while(current_node -> next != NULL) {
printf("Current value: %d\n", current_node -> value);
current_node = current_node -> next;
}
last = current_node;
return last;
}
void add_element(int value, struct node *start) {
struct node *new_node, *ptr_new_node;
new_node = (struct node *) malloc(sizeof(struct node));
ptr_new_node = (struct node *) malloc(sizeof(struct node));
if(start == NULL) {
printf("start: %d\n", start);
new_node -> value = value;
new_node -> next = NULL;
start = new_node;
printf("start: %d\n", start);
printf("Pointer value: %d\n", start -> value);
} else {
struct node *last;
last = transverse_list(start);
new_node -> value = value;
ptr_new_node = NULL;
new_node -> next = ptr_new_node;
}
}
int main() {
struct node *start = NULL;
add_element(2, start);
add_element(3, start);
add_element(5, start);
add_element(7, start);
add_element(11, start);
add_element(13, start);
transverse_list(start);
return 0;
}
哪个打印:
start: 0
start: 7084208
Pointer value: 2
start: 0
start: 7084240
Pointer value: 3
start: 0
start: 7084272
Pointer value: 5
start: 0
start: 7084304
Pointer value: 7
start: 0
start: 7083968
Pointer value: 11
start: 0
start: 7084000
Pointer value: 13
我之前为另一个练习编写了这段代码,它的 sum() 函数改变了 main 函数中指针的值。
void sum(int*, int*, int*);
int main() {
int num1, num2;
int *total;
num1 = 10;
num2 = 15;
sum(&num1, &num2, &total);
printf("Sum: %d\n", total);
return 0;
}
void sum(int *a, int *b, int *t) {
*t = *a + *b;
}
哪个打印:
Sum: 25
我试图将起始指针传递给 add_element 函数(例如:add_element(2, &start)),但它给了我一个分段错误。
为什么第一个示例不像第二个示例那样工作?
解决方案
在添加、删除或排序链表时,“头”指针(您的起始指针)中的值可以更改。
对于被调用的函数来更改该指针的内容,必须将指针的地址传递给它——或者——返回该指针的新内容,并将返回的值分配给“头”指针
推荐阅读
- python-3.x - 循环 Python 基础
- javascript - a-frame entity-positioning and rotation
- javascript - Antd 对其他包的 getFieldDecorator
- node.js - JSON.parse 在 ObjectId 上失败
- java - 我自己的网页没有显示在本地主机上
- python - (PY) 错误消息:无法导入名称 'pkcs1_15'
- apache-spark - 如何将 Virtuoso 分布式版本链接到 Hadoop
- python - 如何重新排序一组数据点以最小化另一组数据点的错误
- python - 如何在添加数组的同时将数组的每个元素保持在一定范围内?
- javascript - 如何使用 javascript 跳过和限制对象数组?