gpt4 book ai didi

c - C 中的列表 : can't add new elements

转载 作者:行者123 更新时间:2023-11-30 14:22:31 26 4
gpt4 key购买 nike

我有一个简单的程序,它初始化一个列表并向其中添加 n 个元素。问题是它无法添加接下来的 n-1 个元素(它只是用第一个元素初始化列表)。我测试了条件,问题似乎出在 add_elem 函数中的 last->next=elem 。程序如下:

#include <stdio.h>
#include <stdlib.h>

typedef struct lista {
int val;
struct lista *next;
} list;

void allocate(list *p) {
printf("Alocating memory...");
p=(list *)malloc(sizeof(list));
if(p==NULL) {
printf("Failed! Exiting program...");
exit(1);
} else printf("Done! \n");
}

void init_list(list *first, list *last) {
printf("Insert first element value: ");
scanf("%d", &(first->val));
printf("Initializing list...\n");
allocate(first);
first->next=NULL;
last=first;
if(first->next==NULL && last==first) {
printf("Done initializing! \n");
printf("Last value: %d\n", last->val);
}
}

void add_elem(list *elem, list *last, int i) {
printf("Insert the %dth element value: ",i);
scanf("%d", &elem->val);
printf("Adding element to list...\n");
allocate(elem);
elem->next=NULL;
last->next=elem;
last=elem;
if(elem->next==NULL && last==elem && last->next==elem) {
printf("Done adding! \n");
printf("Last value: %d\n", last->val);
}
//printf("%d\n", first->next->val);
}

void print_list(list *first) {
printf("\nCurrent list: \n");
list *it;
for(it=first;it!=NULL;it=it->next) {
printf("%d ",it->val);
}
}

int main() {
list first, last, elem;
int n,i;
printf("Insert number of elements: ");
scanf("%d",&n);
init_list(&first,&last);
for(i=2;i<=n;i++) {
add_elem(&elem,&last,i);
}
print_list(&first);
return 0;
}

最佳答案

在您的allocate函数中,您分配内存并将其分配给本地变量p。由于函数返回时不会保存对局部变量的更改,因此该内存将会丢失。

您也不需要分配该内存,因为您已经通过在 main 函数中将列表声明为非指针来分配该内存。

关于c - C 中的列表 : can't add new elements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13685433/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com