【发布时间】:2020-10-20 03:33:21
【问题描述】:
我正在自己研究 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)),但它给了我一个分段错误。
为什么第一个例子不像第二个例子那样工作?
【问题讨论】:
-
您需要使用指针来启动,
add_element(2, &start);以更新到启动值。次要备注不要强制转换 malloc 结果 -
你永远不会改变
startin main。如果要在调用者中修改变量,则必须传递变量的地址。也就是说,你应该调用add_element(2, &start)并将add_element的原型更改为struct node ** -
要么像
add_element(2, &start);那样传递start的地址,要么使用像start = add_element(2, start);这样的返回值。相应地更改add_element()。您的选择。 -
旁注:为了获得最佳风格,从不这样做(例如):
new_node -> value但总是这样做:@ 987654335@ -
你能提供一个更具体的问题吗?这可能有助于更好地了解您对代码输出的期望。
标签: c pointers data-structures