我想創建一個動態數組,我可以在運行時添加 - 但是如果我用x-coords創建3個玩家:4,7和15,然後嘗試打印這些值,輸出爲:0, 33 20762704.C - 創建一個動態的結構數組,結構成員打印錯誤的值?
我是新來的C和指針和我在努力找出它是怎麼了。
#include <stdio.h>
#include <stdlib.h>
// contains data of a player
struct player {
int posX;
int posY;
int gold;
};
// struct for creating a list of players of dynamic size
struct playerList {
struct player p;
struct playerList *next;
};
// add a new player to the list with given coords
struct playerList *make(int x, int y) {
struct playerList *new_player;
new_player = (struct playerList *)malloc(sizeof(struct playerList));
new_player->p.posX = x;
new_player->p.posY = y;
new_player->p.gold = 0;
new_player->next = NULL;
return new_player;
}
// add a player to the list
void addPlayer(struct playerList *list, int x, int y) {
if(list->next) {
addPlayer(list->next,x,y);
}
else {
list->next = make(x,y);
}}
int main() {
struct playerList *players = (struct playerList *)malloc(sizeof(struct playerList));
addPlayer(players, 4,3);
addPlayer(players, 7,7);
addPlayer(players,15,1);
printf("%d\n",players[0].p.posX);
printf("%d\n",players[1].p.posX);
printf("%d\n",players[2].p.posX);
return 0;
}
你應該在分配或分配帶有calloc函數的內存後,將列表下一個變量指針設置爲null。另外,你的列表不是數組,在printf函數中你的行爲是一個數組! –
@ G.Emadi請你能爲我擴展,應該在哪裏設置爲空?我如何參考列表中的每個元素然後打印? – jp963
你永遠不會正確創建第一個節點。只有在列表中已經有至少一個播放器的時候,'addPlayer'功能纔可用於添加播放器 –