Search code examples
cpointerspass-by-referencepass-by-valuefunction-declaration

Pointers are NULL after returning from a function


I'm a beginner in C programming. When the function returns to main(), the two int pointers return NULL, but in the function they point to the correct values. Do you have any suggestions?

int main(){
    int k_attivi=0, n=0, in_game = 0, i, k=0;
    int *array_indici = NULL, *array_ingame = NULL;
    Player *players = NULL;    

    players = upload_players(&k, &in_game, &n, &k_attivi, array_indici, array_ingame);
            
    return 0;
}

Player *upload_players(int *k, int *in_game, int *n_tot, int *k_attivi, int* array_indici,  int* array_in_game){
    FILE *partita = NULL;
    Player *players=NULL;

    partita = fopen("file.bin", "rb");

    if(partita==NULL)
        exit (-1);

    fread(k, sizeof(int ), 1, partita);
    players = calloc(*k, sizeof(Player));
    fread(players, sizeof (Player), *k, partita);
    fread(in_game, sizeof(int ), 1, partita);
    if(*in_game == 1){
       fread(n_tot, sizeof(int), 1, partita);
       fread(k_attivi, sizeof(int), 1, partita);
       array_indici = calloc(*k_attivi, sizeof(int));
       fread(array_indici, sizeof(int), *k_attivi, partita);
       array_in_game = calloc(*k, sizeof(int));
       fread(array_in_game, sizeof(int), *k, partita);
    }
    fclose(partita);
    return players;
}

Solution

  • The pointers are passed to the function by values. This means that the function deals with copies of the values of the passed pointers. Changes of the copies do not influence on the original pointers used as argument expressions.

    You need to pass them by reference through pointers to them.

    For example

    Player *upload_players(int *k, int *in_game, int *n_tot, int *k_attivi, 
                           int** array_indici,  int* array_in_game);
    

    and call the function like

    players = upload_players(&k, &in_game, &n, &k_attivi, &array_indici, &array_ingame);
    

    Within the function you need to dereference the pointers to get a direct access to the original pointers like for example

    *array_indici = calloc(*k_attivi, sizeof(int));
    

    To make it clear compare passing by you pointers and for example the variable k declared in main. The variable k is passed by reference through a pointer to it. Thus changing the variable within the function by dereferencing the pointer to it will be reflected on the original variable k in main. The same way you need to pass the pointers to the function that is by reference through pointers to them.