在这种情况下如何正确使用struct

时间:2014-08-16 21:44:42

标签: c struct

我是C语言编程的新手,我试图找出结构的正确用法,作为一个例子:

int main (int argc, char *argv[])
{
    char player_one = "bob";
    char player_two = "steve";

    enum colour
    {
        P_RED, P_WHITE
    };

    struct player
    {
        char name[MAX_NAME_LEN+1];
        enum colour col;
    };

    int rndNumber;
    srand (time(NULL));
    rndNumber = rand() % 2;
    struct player p1 = {player_one, rndNumber};
    struct player p2 = {player_two, rndNumber};

    printf("%s\n", p1.name);
    printf("%d\n", p1.col);
    printf("%s\n", p2.name);
    printf("%d\n", p2.col);
    return EXIT_SUCCESS;
}

当我尝试编译此代码时,我遇到了几个错误。

warning: initialization makes integer from pointer without a cast [enabled by default]
char player_one = "bob";

warning: missing braces around initializer [-Wmissing-braces]
struct player p1 = {player_one, rndNumber};

warning: (near initialization for ‘p1.name’) [-Wmissing-braces]

warning: initializer element is not computable at load time [enabled by default]

warning: ISO C90 forbids mixed declarations and code [-Wpedantic]
struct player p1 = {player_one, rndNumber};

这样做是为了使p1.name和p2.name不打印,p1.col和p2.col总是打印0,即使rndNumber成功打印随机数。那么我在这里做错了什么? o.O

2 个答案:

答案 0 :(得分:3)

在C中,字符串不是字符,而是字符数组。所以声明他们是这样的:

char *player_one = "bob";

char player_one[] = "bob";

其次,在结构中,您可以将字符串声明为:

char name[MAX_NAME_LEN+1];

char *name;

不同之处在于,在第一种情况下,分配了MAX_NAME_LEN+1个字符,在第二种情况下,name只是一个指针。所以在第一种情况下,你需要复制蜇伤:

strcpy(p1.name, player_one);

在第二种情况下,任务将执行:

p1.name = player_one;

或正如你所做的那样:

p1 = {player_one, rndNumber};

答案 1 :(得分:0)

首先,在main()函数之外定义新类型:

#define MAX_NAME_LEN 100


typedef enum
{
    RED, WHITE
} Color;


typedef struct
{
    char *name;
    Color color;
} Player;

然后,在main()函数中,您可以使用这样的新类型:

char *player_one = "bob";
char *player_two = "steve";

Color redColor = RED;
Color whiteColor2 = WHITE;

Player p1 = { player_one, redColor };
Player p2 = { player_two, whiteColor2 };

printf("%s\n", p1.name);
printf("%d\n", p1.color);
printf("%s\n", p2.name);
printf("%d\n", p2.color);

p1.name = "john";
p2.color = RED;

printf("%s\n", p1.name);
printf("%d\n", p1.color);
printf("%s\n", p2.name);
printf("%d\n", p2.color);