使用malloc时如何解决多重初始化的问题?

时间:2018-04-14 17:34:24

标签: c malloc

我需要使用malloc为一个struct game实例分配内存,并将返回指针存储在游戏的p_game_info中。

这是game.c中相关功能的代码。

void play_game()
{
    struct game *p_game_info = 0;
    struct game *p_game_info = malloc (sizeof (struct game));
}

这是game.h中结构的代码

struct game
{
    char board[3][3];
    char playerNames[2][MAX_NAME_LEN];
    int status;
    boolean finished;
};

在VS中我收到以下错误消息

error C2374: 'p_game_info': redefinition; multiple initialization

我一直在网上搜索类似的问题但是没有成功。

感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

解决方案本身存在错误信息,请勿声明&每次初始化,仅声明p_game_info一次。

void play_game() {
    struct game *p_game_info = malloc (sizeof (struct game));/* declaration & initialization both at a time */
}

答案 1 :(得分:1)

如错误所示,您在函数中初始化指针两次。此外,你也宣布它两次..

尝试只做一次,比如。

void play_game()
{
    struct game *p_game_info = 0;                 // declaring and initializing once
    p_game_info = malloc (sizeof (struct game));  // allotting memory.
}

或者,您可以将两者合并为一行。

void play_game()
{
    struct game *p_game_info = malloc (sizeof (struct game));
}

答案 2 :(得分:0)

将其修复为:

void play_game()
{
    struct game *p_game_info = 0;
    /* struct game* */ p_game_info = malloc (sizeof (struct game));
}

错误意味着它实际上说的是什么。您初始化(定义)了两次相同的变量p_game_info

根据标准,您可能有多个声明,就像这里(应该完美编译)

struct game *p_game_info;
struct game *p_game_info;
struct game *p_game_info;
struct game *p_game_info = 0;
....
void play_game()
{
    p_game_info = malloc (sizeof (struct game));
}

但它必须有只有一个定义(初始化)!

有关C中声明初始化的更多信息,请访问此链接:What is the difference between a definition and a declaration?

修改

正如 Weather Vane 所注意到的那样,多个声明的例子只在文件范围内可以正常 - 并且被称为“tentative declaration