C 中具有动态数组成员的动态结构数组

Dynamic array of structs with dynamic array members in C

struct players playerList[1];
int main(){
    createPlayers(playerList);
    printf("%d", playerList[0].scores[2]);
}
struct players {
    char firstName[20];
    char lastName[20];
    char country[20];
    int scores[1];
    char *cards[1];
};

void createPlayers(struct players currentPlayers[]){
    int numPlayers;
    int numRounds;

    //Get input
    printf("How many players are there? ");
    scanf("%d", &numPlayers);
    printf("How many rounds are there? ");
    scanf("%d", &numRounds);

    //Allocate array of structures
    int* ptr1 = (int*)&currentPlayers;
    ptr1 = ( struct players * ) malloc ( sizeof ( struct players ) * numPlayers);

    //Allocate scores int array
    int* ptr2 = (int *)&currentPlayers[0].scores;
    ptr2 = malloc(numRounds * sizeof(int));

    //Allocate cards string array (array of pointers to char array)
    int* ptr3 = (int*)&currentPlayers[0].cards;
    ptr3 = (int *)malloc(sizeof(int) * numPlayers);
    for( int i = 0; i < numPlayers; i++ )
        currentPlayers[0].cards[i] = malloc( 3 * sizeof *currentPlayers[0].cards[i] );

    //Set scores[2] to 12
    currentPlayers[0].scores[2] = 12;
}

所以我在尝试让它工作时遇到了很多问题。当我打印 playerList[0].scores[2] 时,它会打印 1886220131。我可以打印 playerList[0].scores[0]/scores[1] 就好了,但我似乎无法设置超过第二个索引的任何内容。我是否需要在考虑结构内动态数组的大小的情况下分配原始结构数组?我是 C 的新手,但我尝试用 malloc 做的一切似乎都失败了。任何帮助将不胜感激!谢谢!

当您使用 playerList[1], scores[1], 时...您要求计算机分配一个由 1 个元素组成的数组。然后将数组传递给函数。在函数内部,您分配 ptr1 = currentPlayer,然后将 malloc 与 ptr1 一起使用。这是没有意义的。想一想:x = 1 那么 x = 2 并不意味着 1 = 2。如果你想为你的变量使用 malloc 或 realloc,不要使用 playerList[1], scores[1] 或其他东西,使用 struct Players* playerList 代替:

struct player* playerList;
playerList = (struct players*) malloc (sizeof(struct players) * numPlayers);

接下来,如果要在函数中改变指针的值,必须将pointer的指针传入函数中。也就是说,如果要在createPlayers函数中改变playerList的值,就必须通过&playerList。然后使用:

*currentPlayers = (struct players*) malloc (sizeof(struct players) * numPlayers);

接下来,永远不要将指针的类型强制转换为与声明类型完全不同的新类型。您声明了一个 struct Player** 类型的变量,但您将其转换为 int* 类型。这毫无意义,也会让你的程序变得混乱。

最后,在不需要的时候限制全局变量的使用。例如:

struct players playerList[1];

并且当你使用全局变量时,你不需要将其作为参数传递。

代码编译不成功,修改(struct players *)为(int *),运行正常