首页 > 解决方案 > 为什么返回 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(...)以使其工作?

标签: cpointersmemory

解决方案


推荐阅读