gpt4 book ai didi

c - 数组内容消失

转载 作者:行者123 更新时间:2023-11-30 17:38:17 26 4
gpt4 key购买 nike

我正在尝试将数组传递给函数并用信息填充它。这段代码来自 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;
}

最佳答案

函数filldeck()x递增到51以上,并使用它来索引deck[52]。这样,您就可以超越数组边界并调用未定义的行为

关于c - 数组内容消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22166035/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com