【发布时间】:2013-05-14 10:34:09
【问题描述】:
我试图在我的函数 print_shoe 中使用结构成员 'size',但我的 for 循环没有运行。但是,如果我在 for 循环中用 int 替换 'c->size',它运行得很好
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DECK_SIZE 52
#define NUM_FACES 13
#define NUM_SUITS 4
#define LENGTH_FACES 6
#define LENGTH_SUITS 9
typedef struct cards {
char suits[NUM_SUITS][LENGTH_SUITS];
char faces[NUM_FACES][NUM_FACES];
int suit, face, card, value, size;
int *values[NUM_FACES];
} cards;
char buf[101];
void print_shoe();
void init_decks();
int rand_int();
void shuffle();
int main(void) {
srand( time(NULL) );
int decks_input = 0;
int numberOfDecks = 1;
do {
printf("\nEnter number of decks to be used in the game (1-8):\n\n");
if (fgets(buf, sizeof(buf), stdin) != NULL)
if (sscanf (buf, "%d", &decks_input))
numberOfDecks = decks_input;
} while (numberOfDecks < 1 || numberOfDecks > 8);
cards *shoe = malloc(sizeof(cards) * numberOfDecks * DECK_SIZE);
shoe->size = numberOfDecks * DECK_SIZE;
shuffle(shoe);
print_shoe(shoe);
free(shoe);
return 0;
}
void print_shoe(cards *c) {
int i;
for (i = 0; i < c->size; i++) {
printf("card #%d = %s of %s\n", i+1, c->faces[c[i].face], c->suits[c[i].suit]);
}
}
void init_decks(cards *c) {
int i;
for (i = 0; i < c->size; i++) {
c[i].card = i;
c[i].suit = c[i].card % NUM_SUITS;
c[i].face = c[i].card % NUM_FACES;
}
}
void shuffle(cards *c) {
init_decks(c);
int i, j;
cards tmp;
for (i = c->size - 1; i > 0 ; i--) {
j = rand_int(i + 1);
tmp = c[j];
c[j] = c[i];
c[i] = tmp;
}
}
int rand_int(int n) {
int limit = RAND_MAX - RAND_MAX % n;
int rnd;
do {
rnd = rand();
} while (rnd >= limit);
return rnd % n;
}
编辑:问题已被广泛更新,以回应需要更多澄清的 cmets
【问题讨论】:
-
您的代码无法编译。 1. 将
print_shoe放在main之前 2.(cards *)malloc(...)。更改这些后,它在我的机器上运行良好。 -
@gongzhitaao:演员阵容是不必要的,也是个坏主意。只要确保你有
#include <stdlib.h>,从void*到cards*的转换将隐式完成。 -
您尚未定义
buf或DECK_SIZE,并且缺少<stdio.h>和<stdlib.h>所需的#include指令。你说你的函数“无法访问”结构成员。这意味着什么?当你尝试时会发生什么?您是否收到编译时错误消息?如果是这样,请向我们展示。向我们展示显示问题的complete sample program,并告诉我们问题所在。 -
printf("card #%d = %s of %s\n", i+1, c->faces[c[i].face], c->suits[c[i].suit]);你指的是没有初始化的部分。 -
调试器很容易显示这一点:您初始化了
shoe指向的数组中第一个cards的size,而另一个cards的@ 值未初始化987654339@。当您随机播放时,未初始化的cards之一成为shoe中的第一个条目,并且您正在使用未初始化的变量。size不属于cards结构。