简体   繁体   English

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

[英]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 从我的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 我是编程新手,所以我可能会缺少一些实际上很明显的东西,请不要认为任何事情都是理所当然的

Modification to the copied argument array in the function setup() won't affect local variables in function main() . 在函数setup()对复制的参数array修改不会影响函数main()局部变量。 Dereferencing NULL will invoke undefined behavior and your program just happened to crash . 取消引用NULL将调用未定义的行为,并且您的程序刚巧崩溃

Your setup() should be like this: 您的setup()应该像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM