0
因此,我將此代碼與一個結構和一堆函數結合在一起,並且我希望將這些函數(至少)放在一個單獨的.c文件中。但是,當我這樣做時,它不再識別我擁有的結構卡類型。我該怎麼辦?C - 要將類型struct的函數放在單獨的.c文件中
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
struct card {
int suit;
int value;
};
const char *suitName(int suitNum)
{
switch (suitNum) {
case 1: return "spades";
case 2: return "clubs";
case 3: return "hearts";
case 4: return "diamonds";
}
return "(invalid suit)";
}
struct card makeCard(int suit, int value) {
struct card tempCard;
tempCard.suit = suit;
tempCard.value = value;
return tempCard;
}
struct card *createDeck()
{
const size_t count = 52;
struct card *deck;
/* Allocate new deck of 'count' cards. */
deck = malloc(count * sizeof deck[0]);
if (!deck) {
fprintf(stderr, "createDeck(): Out of memory!\n");
exit(EXIT_FAILURE);
}
int i = 0;
struct card *deckArrayPtr = deck;
for (int suit = 1; suit < 5; suit++)
{
{
for (int value = 1; value < 14; value++) {
deck[i] = makeCard(suit, value);
i++;
}
}
}
return deck;
}
void shuffleDeck(struct card *deck) {
int cardSwitch1, cardSwitch2;
struct card temp;
cardSwitch1 = (rand() % 52);
cardSwitch2 = (rand() % 52);
temp = deck[cardSwitch1];
deck[cardSwitch1] = deck[cardSwitch2];
deck[cardSwitch2] = temp;
}
int main()
{
srand((unsigned int)time(NULL)); //initializing srand
struct card *deckAr = createDeck(); //creating the struct card deck array
for (int i = 0; i < 5000; i++)
{
shuffleDeck(deckAr);
}
for (int a = 0; a < 52; a++) {
//printf("%d of %s\n", deckAr[a].value, suitName(deckAr[a].suit));
printf("%d of %s\n", deckAr[a].value, suitName(deckAr[a].suit));
}
return 0;
}
寫,你把你的'struct' .h文件。將此文件包含在.c文件中。 – Rabbid76