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



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

-1247318248分割故障

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

或者我需要使用可以返回一个指针而不是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("%in", 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。

基本上,当您从函数返回时,局部变量会"消失"。动态分配的内存一直存在,直到显式调用free

希望这有帮助,祝你好运:)