结构和内存分配

时间:2017-12-03 04:46:46

标签: c memory memory-management struct

我可以为这个结构分配内存而不为其中的每个项目分配内存(在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 个答案:

答案 0 :(得分: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 ...,并且更易读和理解。

阅读清单

  1. Is it a good idea to typedef pointers?
  2. Is typedef'ing a pointer type considered bad practice?

答案 1 :(得分: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;
}