2016-06-30 46 views
0

我是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; 

    } 
} 

这里是我的调试会话

Debugger

+0

看看下面的答案。尽管存在一些错误,但代码的整体结构还是可以的。 –

回答

1

问题1

create_team没有做任何事情有用main的照片。您正在更改函数局部变量的值。因此clubmain中保持未初始化状态。您继续使用它,就像它是有效的对象一样,这会导致未定义的行为。

您可以在功能改变为:

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

您在print_club打印也可能Player秒。团队中并不总是SIZE号码Player。行

for (i = 0; i < SIZE; i++) { 

更改为

for (i = 0; i < club->size; i++) { 
+0

它不应该是'club-> team [club-> size]'而不是'club-> team [club-> size -1]'吗? 'club-> size'应该增加,'create_team'的内容实际上应该是'team-> size = 0;' –

+0

@MichaelWalz,是的。 “尺寸”也需要在之后增加。 –

+0

@MichaelWalz,初始化一切都是一个好习惯。这是恕我直言。 –