'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*)¤tPlayers;
ptr1 = ( struct players * ) malloc ( sizeof ( struct players ) * numPlayers);
//Allocate scores int array
int* ptr2 = (int *)¤tPlayers[0].scores;
ptr2 = malloc(numRounds * sizeof(int));
//Allocate cards string array (array of pointers to char array)
int* ptr3 = (int*)¤tPlayers[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;
}
So I've had a lot of problems trying to get this to work. When I print playerList[0].scores[2] it prints 1886220131. I can print playerList[0].scores[0]/scores[1] just fine, but I can't seem to set anything past the second index. Do I need to allocate the original array of structs with the size of the dynamic arrays within the struct in mind? I'm new to C, but everything I try to do with the malloc seems to fail. Any help would be greatly appreciated! Thanks!
Solution 1:[1]

I couldn't compile the code successfully, then I modify (struct players *) to (int *), it runs ok.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Peter Csala |
