C 中的指针。void 函数和作用域中的局部变量

Pointers in C. Local variable in the void function and scope

是否可以在另一个函数范围内的指针列表中创建和插入新元素?仅当我在创建局部变量 n2_4insertEntry 函数中调用 printf 时,此代码才有效,否则输出为

-1247318248 Segmentation fault

我想如果我使用指针,我可以在指针列表中我想要的任何地方创建和插入一个新元素。但它有点像局部变量有限的可见范围。还是我记错了?

或者我需要使用可以 return 一个指针代替 void insertEntry 函数的函数来达到这样的目的?

    // Function to insert a new entry into a linked list. 
#include <stdio.h>

struct entry
{
    int            value;
    struct entry   *next;
};

void insertEntry(struct entry *insertion, struct entry *previous)
{
    struct entry  n2_4;
    n2_4.value = 299;
    struct entry *N2_4 = &n2_4;

    insertion->next = previous->next; // set n2_3.next to point to whatever n2.next was pointing to
    previous->next = insertion;       // set n2.next to point to n2_3

    insertion->value = 250;

    N2_4->next = insertion->next;
    insertion->next = N2_4;
}

void printPlist(struct entry *list_pointer)
{
    while (list_pointer != (struct entry *) 0) {
        printf("%i\n", list_pointer->value);
        list_pointer = list_pointer->next;
    }
    printf("\n");
}

int main(void)
{


    struct entry   n1, n2, n3, n2_3;
    struct entry   *list_pointer = &n1;

    n1.value = 100;
    n1.next = &n2;

    n2.value = 200;
    n2.next = &n3;

    n3.value = 300;
    n3.next = (struct entry *) 0;    // Mark list end with null pointer

    printPlist(list_pointer);

    insertEntry(&n2_3, &n2);

    printPlist(list_pointer);

    return 0;
}

你要找的是动态内存分配,看看malloc

当您从函数中 return 时,基本上是局部变量 "disappear"。动态分配的内存会一直存在,直到您显式调用 free.

希望对您有所帮助,祝您好运:)