首页 文章

结构和内存分配

提问于
浏览
1

我可以为这个结构分配内存而不为其中的每个项目分配内存(在C中)吗?

typedef struct _game {
        int grid[SIZE][SIZE];
        int array[10];
        Player player[MAX_PLAYERS];
        int currentPlayer;
    } game;

这些是在单独的头文件中(并且播放器是在与游戏相同的文件中实现的结构):

typedef struct _game *Game;
    typedef struct _player *Player;

我只是想知道,当我创建一个新的游戏实例时,我是否需要为游戏中的每个玩家分配内存(使用calloc或malloc for exmaple)(4个玩家)?我认为,因为我已经在游戏结构中有一系列玩家(或指向玩家的指针)(并且这个数组大小没有改变),所以我只需要为游戏结构本身分配内存 . 是这样的吗?如何使用内存分配?具体如何与结构一起使用?我是否还需要为结构中的所有其他项分配内存?

2 回答

  • 1

    那么结构的设计方式,你需要分配个别玩家 .

    解决方案-1

    你会做的

    Game game = malloc(sizeof *game);
    

    然后你有 MAX_PLAYER_Player 指针变量 . 所以它会是这样的

    for(size_t  i = 0; i<MAXPLAYERS; i++)
          game->player[i]= malloc(sizeof *game->player[i]);
    

    不鼓励在 typedef 下隐藏指针 . 这是一个不好的做法 . 此外,您需要检查 malloc() 的返回值,并在完成后使用动态分配的内存 .

    你做了什么?

    Player player[MAX_PLAYERS]; 是指针数组,不是 _player 变量数组 . 这就是为什么每个指针变量需要分配一些内存 . 这样您就可以将玩家数据存储到其中 .


    解决方案-2

    你可以这样做:

    typedef struct _game {
        int grid[SIZE][SIZE];
        int array[10];
        Player player;
        int currentPlayer;
    } game;
    

    然后分配10个玩家变量内存并将 malloc 返回的值分配给 player .

    Game game = malloc(sizeof *game);
    ..
    game->player = malloc(sizeof *game->player *MAX_PLAYERS);
    ..
    

    解决方案-3

    typedef struct _game {
        int grid[SIZE][SIZE];
        int array[10];
        struct _player player[MAX_PLAYERS];
        int currentPlayer;
    } game;
    

    那么你不需要为玩家单独分配 . 它里面已经有 MAX_PLAYERstruct _player 变量 .


    当你问起 typedef 时,你可以简单地这样做

    typedef struct _game {
        int grid[SIZE][SIZE];
        int array[10];
        Player player[MAX_PLAYERS];
        int currentPlayer;
    } game;
    
    ...
    ...
    game *mygame = malloc(sizeof *mygame);
    

    这样可以达到目的 - 并且可以避免输入 struct ... ,而且更易读和理解 .

    阅读清单

  • 0

    我是否还需要为结构中的所有其他项分配内存?

    不,结构中的所有项都将自动分配内存 .

    这是分配的例子,它也清除结构内存:

    #include <stdio.h>
    
    #define SIZE 10
    #define MAX_PLAYERS 20
    
       typedef struct _player {  
            char name[10];
            int i;
        } Player;
    
    
        typedef struct _game {
            int grid[SIZE][SIZE];
            int array[10];
            Player player[MAX_PLAYERS];
            int currentPlayer;
        } game;
    
    int main()
    {
       game *g = calloc(1, sizeof (game));
    
       return 0;
    }
    

相关问题