我是C的noob,並創建這個程序來幫助我學習。目的是將足球運動員添加到球隊並打印信息。c中的結構打印字段(動態內存分配)
我試圖打印我的俱樂部結構的字段,但是當我的程序到達我的打印方法時,我所有的值都是垃圾或地址。我怎樣才能得到 「真實」 價值
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 8
typedef struct player {
int id;
char *position;
} Player;
typedef struct club {
int size;
Player *team[SIZE];
} Club;
Player *create_player(int id, const char *description);
void create_team(Club *club);
void print_club(const Club *club);
void add_player_to_club(Club *club, int id, const char *position);
int main() {
Club club;
create_team(&club);
add_player_to_club(&club, 1, "forward");
add_player_to_club(&club, 2, "goalie");
print_club(&club);
return 0;
}
Player *create_player(int id, const char *description){
Player *player;
player = malloc(sizeof(Player));
if(description == NULL){
player->position = NULL;
} else {
player->position = malloc(strlen(description) + 1);
strcpy(player->position, description);
player->id = id;
}
return player;
}
void create_team(Club *team){
team = malloc(sizeof(Club));
if (team == NULL) {
return;
} else {
team->size = 0;
}
}
void print_club(const Club *club) {
int i = 0;
if (club == NULL) {
return;
} else if (club->size == 0) {
printf("No team members\n");
} else {
for (i = 0; i < SIZE; i++) {
printf("Id: %d Position: %s\n", club->team[i]->id,
club->team[i]->position);
}
}
}
void add_player_to_club(Club *club, int id, const char *position){
if (club == NULL || club->size >= SIZE) {
return;
} else {
Player player = *create_player(id, position);
club->team[club->size -1] = &player;
}
}
這裏是我的調試會話
看看下面的答案。儘管存在一些錯誤,但代碼的整體結構還是可以的。 –