-1

I need to use malloc to allocate memory to one instance of struct game and store the return pointer in p_game_info for a game.

This is the code for the relevant function in game.c

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

This is the code for the struct in game.h

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

In VS I am getting the following error message

error C2374: 'p_game_info': redefinition; multiple initialization

I have been searching online for a similar problem but have been unsuccessful.

Thanks for your help.

Susie
  • 21
  • 3
  • the problem is not malloc but you declared the `p_game_info` twice in the function play_game() – Dr Deo Apr 14 '18 at 17:44

3 Answers3

1

Solution is there in error message itself, don't declare & initialize every time, declare p_game_info only once.

void play_game() {
    struct game *p_game_info = malloc (sizeof (struct game));/* declaration & initialization both at a time */
}
Achal
  • 11,629
  • 2
  • 14
  • 34
1

As the errors says, you are initializing the pointer twice in your function. Also, you are declaring it also twice..

try doing both only once, something like.

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

Alternatively, you can combine both in one line.

void play_game()
{
    struct game *p_game_info = malloc (sizeof (struct game));
}
Haris
  • 11,514
  • 6
  • 36
  • 63
0

Fix it to:

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

The error means what it actually says. You initialized (defined) twice the same variable p_game_info.

According to the standard, you may have multiple declarations, like here (which should compile perfectly)

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));
}

But it must have only one definition (initialization)!

More about declaration and initialization in C is in this link: What is the difference between a definition and a declaration?

EDIT

As noticed by Weather Vane, the example of multiple declarations, is OK only at a file scope - and is called a "tentative declaration"

Alex Lop.
  • 6,640
  • 1
  • 24
  • 43