【发布时间】:2014-03-04 07:55:16
【问题描述】:
我正在尝试将数组传递给函数并用信息填充它。这段代码来自一个练习,以学习 C 中的按位运算的基本知识,但是当数组“deck”被解析为函数“filldeck”时,它被破坏了。到那里为止,它按预期工作。
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
typedef unsigned char card;
typedef unsigned char pairs;
/* arrays for the names of things */
static char *suits[] = {"Hearts","Diamonds","Clubs","Spades"};
static char *values[]= {"Ace","Two","Three","Four","Five","Six",\
"Seven","Eight","Nine","Ten","Jack",\
"Queen","King"};
static char *colour[]= {"Black","Red"};
/* function prototypes */
void printcard(card c); /* Displays the value of a card*/
void printdeck(card deck[52]); /* prints an entire deck of cards*/
void filldeck(card deck[52]); /* Populates a deck of cards */
void shuffle(card deck[52]); /* Randomizes the order of cards */
int compareface(const void* c1,const void *c2);
/* compares the face value of 2 cards, suitable to pass to qsort
as the fourth argument */
pairs findpairs(card *hand); /* finds any pairs in a hand */
int main()
{
card deck[52],*deckp;
card hands[5][5],handssorted[5][5];
pairs numpairs[5],highest;
int hand,cd,winner;
srand(time(NULL)); /* seed the random number generator */
/*populate and shuffle the deck */
filldeck(deck);
scanf("%*c*");
printdeck(deck);
scanf("%*c");
shuffle(deck);
printdeck(deck);
}
void filldeck(card deck[52])
{
/* populate the deck here */
int x = 0;
//hearts
for(int y = 64; y <=112;y += 4)
{
deck[0 + x] = y;
x ++;
}
//diamonds
for(int y = 1; y <=49;y += 4)
{
deck[0 + x] = y;
x ++;
}
//clubs
for(int y = 2; y <=50;y += 4)
{
deck[0 + x] = y;
x ++;
}
//spades
for(int y = 67; y <=115;y += 4)
{
deck[0 + x] = y;
x ++;
}
printf("Deck filled");
return;
}
【问题讨论】:
-
编译所有警告和调试信息(例如
gcc -Wall -g)。学习使用调试器(例如gdb)。 -
为什么写
0 + x?结果将始终为x。 -
“损坏”是什么意思?
-
你的
deck应该只保留 52 个元素,但你的函数超出了它的大小 -
如果你正在做我认为你是你的牌组的事情,应该简单地加载 0..51 的值,然后随机洗牌。西装和等级是计算的。一张牌“花色”是
(deck[i] % 4)返回一个 0..3 值以在您的suits[]数组中索引花色的文本名称。同样,一张卡片的rank(它的数值)是(deck[i] % 13),从0..12返回一个值,并再次用于索引values[]以获得rank的文本名称。
标签: c arrays corruption