gpt4 book ai didi

c - 结构和内存分配

转载 作者:太空宇宙 更新时间:2023-11-04 03:19:44 24 4
gpt4 key购买 nike

我是否可以只为此结构分配内存而不为其内部的每个单独项分配内存(在 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;

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

最佳答案

结构的设计方式确实需要分配个别玩家。

解决方案-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个player变量内存,将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 ... 并且它更具可读性和可理解性。

阅读 list

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

关于c - 结构和内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47615346/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com