-1

I have an add function and use a realloc to take in the data from a struct and store it. But when I print it out, it says that it's empty, which comes from my display function. How can I fix this?

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);
    }
}

My main function looks like this:

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;
ilim
  • 4,477
  • 7
  • 27
  • 46
Adrian
  • 11
  • 1
  • 4

2 Answers2

1

The updated value of head is never returned to the caller. Use:

void additem(food **head, int index) {

    *head = (food*)realloc(*head, sizeof(food)*(index + 1));

and call it like:

    additem(&foods, nofood);

When you pass food you pass the value of food. Although the function updates this value, the value is not communicated back to the caller. This is called "call-by-value". If you pass the address of food, and assign to the thing (variable) that head points to, you have changed the caller's value. This is called "call-by-reference" (though strictly speaking, passing any pointer is call-by-reference).

Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41
0

Consider this simple program:

void foo(int bar)
{
  bar = bar + 1;
}

int main()
{
  int test = 4;
  foo(bar);
  printf("bar = %d\n", bar);
}

What is the output of this simple program? If you know the answer you know the answer to your problem.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115