Search code examples
cpointerspass-by-valuefunction-calls

Losing pointer information in function


I'm doing an exercise for my programming subject, it's a Hospital Manegment program. And in the beginning of the program i need to send the information from a .txt to a dynamic struct. And I've been battling the last few hours why am I losing the data.

Why does my head pointer is null after exiting this function and i try to print it out ? Shouldn't the pointer keep the information.

Thanks in advance. Ps: If you have any tip for my algorithm feel free to say.

void dump_med(struct medico *head_m)
{
    int i = 1;
    struct medico *new_med;
    struct medico *temp_m;

    FILE *f = fopen(M_FILE, "r");
    new_med = malloc(sizeof(struct medico));
    temp_m = malloc(sizeof(struct medico));

    if(f == NULL)
    {
        printf("Erro a abrir o ficheiro\n");
        return;
    }

    if( new_med == NULL || temp_m == NULL)
    {
        printf("Erro a alocar a memória\n");
        return;
    }
    while(!feof(f))
    {   
        new_med = realloc(new_med, sizeof(struct medico) * i);
        if( new_med == NULL)
        {
            printf("Erro a realocar a memória\n");
            return;
        }
        fscanf(f, "%[^\n]", new_med->nome);
        fscanf(f, "%s %d.%d--%d.%d\n", new_med->especialidade, &(new_med->entrada.h), 
            &(new_med->entrada.m), &(new_med->saida.h), &(new_med->saida.m));
        temp_m = new_med;
        temp_m->next = head_m;
        head_m = temp_m;
        new_med = new_med->next;
        i++;

    }
    free(new_med);
    free(temp_m);
    fclose(f);
}

Solution

  • In C, all parameters are pass by value. So when modify head_m, you're only modifying a local variable.

    If you want changes to be reflected in the calling function, pass the address of the variable in question, then dereference the pointer variable in the function.

    void dump_med(struct medico **head_m)
    {
        ...
        temp_m->next = *head_m;
        *head_m = temp_m;
        ...
    }
    

    Then you call it like this:

    dump_med(&head_m);