我正在尝试执行以下操作,但编译器抱怨括号,但是,我无法找到替代方法。
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"};
}
我意识到有几个可能的重复线程,但没有一个让我在赛道上。我希望你们中的一个可以:)谢谢
答案 0 :(得分: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));
}
答案 1 :(得分: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);
答案 2 :(得分: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"}
};
答案 3 :(得分: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。)