[英]error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token in struct
I'm getting the error when compiling with gcc -Wall -std=c99: 使用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. 您不能在struct声明中编写代码。 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. 如果您认为每只hand
每次都包含5
张牌,那么可以添加这样的卡片。
In the first case you need to allocate the card
s and then free it when you are done working with it. 在第一种情况下,您需要分配card
,然后在完成使用后将其释放。
You can't "do things" with the struct
members when you define the struct
. 定义struct
时,不能对struct
成员“做事”。
So Card *cards = malloc(sizeof(Card)*5);
因此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; 一种解决方案是构建一个init_card
函数,该函数将struct card*
作为输入参数。 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. 如果您还构建了相应的free_card
函数,则最终会得到很好的扩展。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.