打印c中的结构字段(动态内存分配)

时间:2016-06-30 14:46:18

标签: c memory-management

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

1 个答案:

答案 0 :(得分:1)

问题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 print_club进行打印。团队中的SIZE个数量始终不会Player。改变行

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

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