C语言 使用malloc()[指针表示法]动态分配和打印值


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define SUITS 4
#define RANKS 13
#define DECK_SIZE 52
#define MAX 9
typedef struct
{
char *rank;
char *suit;
char *colour;
}Card;
Card* make_deck();
void print(Card*);
int main()
{
Card *deck = make_deck();
printf(" ***************Original Deck ***************n");
print(deck); /*print original deck */

return 0;
}
Card* make_deck()                                                                 {

char *ranks[] = { "King", "Queen", "Jack", "10", "9", "8", "7", "6", "5", "4", "3", "2", "Ace" };
char *suits[] = { "Spades", "Clubs", "Hearts", "Diamonds" };
/*allocate space for 52 cards on the heap */
Card * deck=malloc(DECK_SIZE * sizeof(char));
/*put cards into the space */
for(int i=0;i<DECK_SIZE;i++){
deck[i].rank = ranks[i%RANKS];


/*Set the ranks,suits and colours of the cards  */
strncpy(deck[i].suit, suits[i/RANKS], MAX);
return deck;
}
}
/*print the deck to the screen*/
void print(Card *deck) {
int i=0;
for(i=0;i<DECK_SIZE;i++){
printf("%5s of %-12s",deck[i].rank,deck[i].suit);
}
}

我正在执行我的C程序,并将卡片(花色,排名)的值存储在相应的数组中,但每次运行程序时都会出现分段错误。我不确定我哪里出错了。欢迎提出任何建议谢谢。

您的意思是为52个Card分配空间,但是您为52个char分配了空间。分配内存的行应该是Card * deck = (Card *) malloc(DECK_SIZE * sizof(Card));

最新更新