Frans
Frans

Reputation: 45

Program crash accessing dynamically allocated array from function in C

thanks for taking the time to read this. I'm having my program crash as soon as i try to access an array which was previously dynamycally allocated in a function. Here's some code

//function to allocate my array, gives an array as return
Player* allocate(Player **a, int n) { 
    *a = (Player *) malloc(sizeof(Player)*(n));
    return *a;
}

//populating my allocated array, return an array
Player* initializePlayers(Player *a, int n){
    int i=0;
    char tmp[MAXCHAR];
    for(i=0; i<n; i++){
        printf("Insert player name %d\n", i);
        scanf("%s", tmp);
        strcpy(a[i].playerName,tmp);
        printf("Player %s assigned.\n", a[i].playerName);
        a[i].playerNumber=i;
    }
return a;
}

//setup function which includes both the above ones, called from main
void setup(Player *array, int *nPlayers){
    int done=0;
    while (done==0){
    printf("How many players?\n");
    scanf("%d", nPlayers);
    if (*nPlayers <2 || *nPlayers>8){
        printf("Choose between 2 and 8\n");
            waitFor(2);
            clear();
            done=0;
       }
    else done=1;
    }
    allocate(&array, *nPlayers);
    initializePlayers(array, *nPlayers);
}

from my main

    Player * array=NULL;
    //I'm passing nPlayers because i want the value to be saved and available on my main
    setup(array, &nPlayers); 

    for (i=0; i<nPlayers; i++){
        printf("It's %s 's turn\n", (array)[i].playerName);
        dices=diceRoll(&same);
    }

I'm fairly new to programming so I might be missing something that is actually pretty obvious, please don't take anything for granted

Upvotes: 1

Views: 147

Answers (1)

MikeCAT
MikeCAT

Reputation: 75062

Modification to the copied argument array in the function setup() won't affect local variables in function main(). Dereferencing NULL will invoke undefined behavior and your program just happened to crash.

Your setup() should be like this:

void setup(Player **array, int *nPlayers){

    /* ... */

    allocate(array, *nPlayers);
    initializePlayers(*array, *nPlayers);
}

and it should be called like this:

Player * array=NULL;
//I'm passing nPlayers because i want the value to be saved and available on my main
setup(&array, &nPlayers);

Upvotes: 3

Related Questions