c - 为什么返回 void 的函数不保存值?
问题描述
我想我错过了一些关于指针和内存的重要内容。这是所需的最少代码:
#include <stdio.h>
#include <stdlib.h>
struct node {
int value;
struct node* next;
};
struct node* init(int value) {
struct node* head = (struct node*)malloc(sizeof(struct node));
if (!head) return NULL;
head->value = value;
head->next = NULL;
return head;
}
void insert_back(struct node* head, int value) {
if (!head) return;
struct node* temp = head;
struct node* new = (struct node*)malloc(sizeof(struct node));
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = new;
new->value = value;
new->next = NULL;
return;
}
struct node* insert_front(struct node* head, int value) {
struct node* temp;
struct node* new = (struct node*)malloc(sizeof(struct node));
new->value = value;
new->next = head;
temp = head;
head = new;
head->next = temp;
return new;
}
void insert_front_2(struct node* head, int value) {
struct node* temp;
struct node* new = (struct node*)malloc(sizeof(struct node));
new->value = value;
new->next = head;
temp = head;
head = new;
head->next = temp;
}
void print_list(struct node* head) {
if (!head) return;
struct node* temp = head;
int i = 0;
while (temp != NULL) {
printf("At position %d value %d \n", i, temp->value);
i++;
temp = temp->next;
}
}
int main() {
struct node* head = init(5);
insert_back(head, 7);
insert_back(head, 9);
insert_back(head, 12);
insert_back(head, 13);
insert_back(head, 14);
insert_back(head, 15);
head = insert_front(head, 100);
insert_front_2(head, 200);
print_list(head);
free(head);
return 1;
}
问题与功能有关void insert_front_2(...)
。我不明白为什么struct ndoe * instert_front
工作得很好,但是insert_front_2
一旦我进入主要位置时就不会握住新头 - 也就是说,当我打印列表时,不会打印新头。有任何想法吗?我应该如何修改void insert_front_2(...)
以使其工作?
解决方案
推荐阅读
- vue.js - 选择带有自定义标签的单选按钮
- nginx - Nginx 仅适用于 80 以外的端口
- python - Python:通过对新行的列值进行采样来生成合成数据
- c# - Can't get query parameter from HttpRequestData
- python - 需要将python文件导入机器人文件
- python - AppIndicator 在登录时启动的系统条件
- c++ - OpenGL执行错误(可能是电脑)
- node.js - 当我检查我的 Google chrome 浏览器控制台时出现此错误:“GET http://localhost:3000/posts 404 (Not Found)”
- r - 如何限制 R Shiny 中的滑块移动量?
- python - 何时使用 nonlocal 关键字?