簡體   English   中英

錯誤:結構中'='標記之前的預期':',',',';','}'或'__attribute__'

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

使用gcc -Wall -std = c99編譯時出現錯誤:

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

這是我的代碼發生錯誤的地方

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

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

這些結構之前我所擁有的只是頭文件包括

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

您不能在struct聲明中編寫代碼。 那是錯的。

我敢打賭這會解決錯誤

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

然后,當您用該類型聲明了適當的變量時,便可以為其分配。

也可以

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

如果您認為每只hand每次都包含5張牌,那么可以添加這樣的卡片。

在第一種情況下,您需要分配card ,然后在完成使用后將其釋放。

定義struct時,不能對struct成員“做事”。

因此Card *cards = malloc(sizeof(Card)*5); 沒有意義,並且編譯器發出診斷信息。

一種解決方案是構建一個init_card函數,該函數將struct card*作為輸入參數。 然后您在那里進行初始化。 如果您還構建了相應的free_card函數,則最終會得到很好的擴展。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM