简体   繁体   中英

error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token in struct

I'm getting the error when compiling with gcc -Wall -std=c99:

pokerhand.c:20:17: error: expected ':', ',', ';', '}' or '__attribute__' before '=' token
Card *cards = malloc(sizeof(Card)*5);

here is my code where the error is happening

typedef struct card 
{
    char suit;
    char *face;
} Card;

typedef struct hand 
{
    Card *cards = malloc(sizeof(Card)*5);
    char *result;
} Hand;

all I have before these structs is header includes

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>

You can't write code inside a struct declaration. That is wrong.

I bet this would solve the error

typedef struct hand 
{
    Card *cards;
    char *result;
} Hand;

And later you can allocate to it when you have proper variable declared with that type.

Also this would work

typedef struct hand 
{
    Card cards[5];
    char *result;
} Hand;

If you think that each hand would contain 5 card every single time then yes you can add it like this.

In the first case you need to allocate the card s and then free it when you are done working with it.

You can't "do things" with the struct members when you define the struct .

So Card *cards = malloc(sizeof(Card)*5); makes no sense, and the compiler issues a diagnostic.

One solution is to build an init_card function, that takes a struct card* as an input parameter; and you perform your initialisation there. If you also build a corresponding free_card function you'll end up with something that scales up remarkably well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM