Structs中的结构依次排列

时间:2014-03-16 04:16:35

标签: c pointers struct typedef

我想做一个关于二十一点游戏的程序,但我尝试的是另一种方式,但我不知道是否有可能。 代码已编译但在启动程序时,它会关闭:

blackjack.exe已停止工作 一个问题导致程序停止正常工作。如果有可用的解决方案,Windows将关闭该程序并通知您。

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

#define NUMBER_PLAYERS 6
#define NUMBER_SUITS 4
#define NUMBER_RANKS 13
#define NUMBER_CARDS (NUMBER_SUITS * NUMBER_RANKS)

typedef unsigned int uint;

typedef struct
{
    uint suit;
    uint rank;
} Card;

typedef struct card
{
    Card card;
    struct card *next;
} card;

typedef struct match
{
    card *list;
    struct match *next;
} Match;

typedef struct
{
    char *name;
    uint wins;
    uint losses;
    Match *match;
} Player;

void main(void)
{
    Player player[NUMBER_PLAYERS];
    uint i, j, count = 0;
    char *op;
    for(i = 0; i < NUMBER_PLAYERS; i++)
    {
        printf("Name: ");
        scanf("%[^\n]s%*c", &player[i].name);
        printf("\n\n");
        player[i].losses = 0;
        player[i].wins = 0;
        player[i].match->next = NULL;
        player[i].match->list->next = NULL;
    }
    getchar();
}

2 个答案:

答案 0 :(得分:1)

问:为什么不只是Player player[NUMBER_PLAYERS];?为什么指向数组的指针,而不仅仅是数组?

建议:改为scanf("s%", player[i]->name);我假设你想要的只是输入名字,对吗?

建议:创建一个或多个&#34; init_xxx)&#34;函数用于根据需要初始化您的结构(包括子结构和/或链接指针)。

问:player[i]->name;应该做什么?为什么不删除该行?

问:你是什么意思&#34;当启动程序时,它关闭:这个程序已经停止工作......&#34;?我注意到你有一个&#34; getchar()&#34; - 它是否跳过getchar()&#34;并终止?更改&#34; scanf()&#34;时行为是否会改变?在任何情况下,您都会收到错误消息吗?

问:你用的是什么编译器?你是在Windows,Linux还是其他东西&#34;?您使用的是IDE(如Eclipse / CDT或Visual Studio)吗?

答案 1 :(得分:1)

Player *player[NUMBER_PLAYERS];  // it's an array of pointers, 

- &GT;在使用它之前,数组中的任何项都需要指向一个Player

    typedef struct match
{
    card *list;                  // it's a pointer
    struct match *next;
} Match;

- &GT;卡*列表也需要指向初始化卡

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

#define NUMBER_PLAYERS 6

typedef unsigned int uint;

typedef struct
{
    uint suit;
    uint rank;
} Card;

typedef struct card
{
    Card card;
    struct card *next;
} card;

typedef struct match
{
    card *list;
    struct match *next;
} Match;

typedef struct
{
    char *name;
    uint wins;
    uint losses;
    Match *match;
} Player;

void main(void)
{
    Player player[NUMBER_PLAYERS];
    card cardList[NUMBER_PLAYERS];
    uint i;
    for(i = 0; i < NUMBER_PLAYERS; i++)
    {
        player[i] = NULL;
        printf("Name: ");
        scanf("%[^\n]s%*c", &player[i].name);
        printf("\n\n");
        player[i].name;
        player[i].losses = 0;
        player[i].wins = 0;
        player[i].match->next = NULL;
        player[i].match.list = &cardList[i];
        player[i].match.list->next = NULL;
    }
    getchar();
}