我是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;
}
}
这是我的调试会话的照片
问题1
create_team
没有为做任何有用的事情main
。您正在更改函数局部变量的值。因此,在中club
仍未初始化main
。您将继续使用它,就像它是有效对象一样,这是导致未定义行为的原因。
您可以将该函数更改为:
void create_team(Club *team){
team->size = 0;
for (int i = 0; i < SIZE; ++i )
{
team->team[i] = NULL; // Unfortunate choice of variable names
// but should be OK.
}
}
问题2
您将在中存储指向函数局部变量的指针add_player_to_club
。该指针变为无效,函数返回。
Player player = *create_player(id, position);
club->team[club->size -1] = &player; // Problem
更改为:
club->team[club->size] = create_player(id, position);
club->size++;
问题3
您打印也可能Player
S IN print_club
。团队中并不总是SIZE
有Player
s个。换线
for (i = 0; i < SIZE; i++) {
至
for (i = 0; i < club->size; i++) {
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句