3

我正在尝试执行以下操作,但编译器抱怨括号,但是,我找不到替代方法。

struct cards {
  char faces[13][6], suits[4][9];
}

typedef struct cards cards;

void init_struct(cards *s) {
  s->suits = {"hearts","spades","clubs","diamonds"};
  s->faces = {"ace","two","three","four","five",
              "six","seven","eight","nine"
              "ten","jack","queen","king"};
}

我意识到那里有几个可能的重复线程,但没有一个让我走上正轨。我希望你们中的一个可以:)谢谢

4

4 回答 4

2
#include <string.h>

typedef struct cards {
    char faces[13][6], suits[4][9];
} cards;

cards base_card = {
    {"ace","two","three","four","five",
     "six","seven","eight","nine", //forgot "," at nine after
     "ten","jack","queen","king"},
    {"hearts","spades","clubs","diamonds"}
};

void init_struct(cards *s) {
    memcpy(s, &base_card,sizeof(cards));
}
于 2013-05-12T09:35:33.943 回答
0

直接初始化语法只能用于初始化,不能用于赋值。您不能这样做,例如:

char p[2][5];
p = {"a", "b"}; //error

这就是它无法编译的原因。尝试strcpy逐个字符串

strcpy(s->suits[0], "hearts");
strcpy(s->suits[1], "spades");
...etc

或者,初始化一个临时数组,然后复制它

char suits_tmp[4][9] = {"hearts","spades","clubs","diamonds"};
memcpy(s->suits, suits_tmp, 4*9);
于 2013-05-12T09:23:57.657 回答
0

const char *在您的内部使用struct(我假设不需要修改西装/面值的实际内容)并单独初始化它们:

struct cards {
    const char *suits[4];
    const char *faces[13];
};

typedef struct cards cards;

void init_struct(cards *s)
{
    s->suits[0] = "hearts";
    s->suits[1] = "spades";
    s->suits[2] = "clubs";
    s->suits[3] = "diamonds";
    s->faces[0] = "ace";
    s->faces[1] = "two";
    s->faces[2] = "three";
    s->faces[3] = "four";
    s->faces[4] = "five";
    s->faces[5] = "six";
    s->faces[6] = "seven";
    s->faces[7] = "eight";
    s->faces[8] = "nine";
    s->faces[9] = "ten";
    s->faces[10] = "jack";
    s->faces[11] = "queen";
    s->faces[12] = "king";
}

当然,如果您只想要一套一次性的卡片,这是合理的,那么这将起作用:

struct
{
    const char *suits[4];
    const char *faces[13];
} cards =
{
    {"hearts","spades","clubs","diamonds"},
    {"ace","two","three","four","five",
        "six","seven","eight","nine",
        "ten","jack","queen","king"}
};
于 2013-05-12T09:28:16.450 回答
0
#include <string.h>
#include <stdio.h>

struct cards {
  const char** suits;
  const char** faces; 
};

typedef struct cards cards;

const char* suits[4] = {"hearts","spades","clubs","diamonds"};
const char* faces[13] = {"ace","two","three","four","five",
              "six","seven","eight","nine"
              "ten","jack","queen","king"};
int main()
{
    cards deck;
    deck.suits = suits;
    deck.faces = faces;
    printf(deck.suits[0]);
    return 0;
}

这也有效。不使用指针。

澄清

我知道我的答案是快速而肮脏的,但是没有strcpy或没有memcpy一长串作业。如果您的计划是为您的游戏使用标准纸牌,那么无论如何这将是一组不变的值。如果您的意图是拥有不同类型的套牌,那么我的回答可能不够充分。是的,它没有init_struct功能,但您可以根据自己的意图轻松修改它(因为我不精通 C 和 malloc。)

于 2013-05-12T09:31:03.157 回答