程序崩溃从C中的函数访问动态分配的数组

时间:2016-07-14 09:05:25

标签: c arrays dynamic structure allocation

感谢您花时间阅读本文。 我尝试访问之前在函数中动态分配的数组时,我的程序崩溃了。这是一些代码

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

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

我对编程很新,所以我可能会遗漏一些实际上非常明显的东西,请不要把任何事情视为理所当然

1 个答案:

答案 0 :(得分:2)

对函数array中复制的参数setup()的修改不会影响函数main()中的局部变量。 Dereferencing NULL will invoke undefined behavior并且您的程序只是碰巧崩溃了

您的setup()应该是这样的:

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

    /* ... */

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

应该像这样调用:

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