【发布时间】:2017-10-25 12:34:52
【问题描述】:
我有一个 add 函数并使用 realloc 从结构中获取数据并存储它。但是当我打印出来时,它说它是空的,这来自我的显示功能。我该如何解决这个问题?
void additem(food *head, int index) {
head = (food*)realloc(head, sizeof(food)*(index + 1));
if (head != NULL) {
printf("Enter name: ");
gets((head + index)->name);
printf("Type unit of meauserement: ");
gets((head + index)->unit);
printf("Enter value: ");
scanf("%d", &(head + index)->data);
}
else {
printf("\nExiting!!");
free(head);
}
}
我的主要功能是这样的:
food *foods = NULL;
int option, nofood = 0;
while (1) {
system("CLS");
printf("1 - add food\n2 - print shopping list\n3 - delete item\n4 - change amount\n5 - end\nWhat do you want to do? ");
scanf("%d", &option);
clear();
switch (option) {
case 1: additem(foods, nofood);
break;
【问题讨论】:
-
你知道吗?函数外,
head保持不变!! -
另外,
noFood永远不会改变,导致index中的additem永远为 0。 -
@SouravGhosh 这无济于事,因为这正是所要求的。更有建设性。
标签: c function struct linked-list