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;
}
所以我在試圖讓它發揮作用時遇到了很多問題。當我列印 playerList[0].scores[2] 時,它會列印 1886220131。我可以列印 playerList[0].scores[0]/scores[1] 就好了,但我似乎無法設定超過第二個索引的任何內容。我是否需要考慮結構中動態陣列的大小來分配原始結構陣列?我是 C 新手,但我嘗試用 malloc 做的一切似乎都失敗了。任何幫助將不勝感激!謝謝!
uj5u.com熱心網友回復:
當您使用playerList[1], scores[1],...您要求計算機分配一個由 1 個元素組成的陣列。然后將陣列傳遞給函式。在您分配的函式內部ptr1 = currentPlayer,然后將 malloc 與ptr1. 這是沒有意義的。想一想:x = 1thenx = 2并不意味著1 = 2. 如果你想為你的變數使用 malloc 或 realloc ,不要使用playerList[1], scores[1]或其他東西,請struct Players* playerList改用:
struct player* playerList;
playerList = (struct players*) malloc (sizeof(struct players) * numPlayers);
接下來,如果要更改函式中指標的值,則必須將指標的指標傳遞給函式。也就是說,如果你想改變playerListincreatePlayers函式的值,你必須通過&playerList. 然后使用:
*currentPlayers = (struct players*) malloc (sizeof(struct players) * numPlayers);
接下來,永遠不要將指標的型別轉換為與宣告的型別完全不同的新型別。您宣告了一個 type 變數,struct Player**但您將其強制轉換為 type int*。這是沒有意義的,也會讓你的程式混亂。
最后,在不需要時限制使用全域變數。例如:
struct players playerList[1];
并且當你使用全域變數時,你不需要將它作為引數傳遞。
uj5u.com熱心網友回復:
我無法成功編譯代碼,然后我將(struct player *)修改為(int *),它運行正常。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/420514.html
標籤:
上一篇:我在填充這個陣列時出錯了嗎?
下一篇:為什么從2開始回圈?
