簡體   English   中英

使用 malloc() [指針表示法] 動態分配和打印值

[英]Dynamically allocating and printing values using malloc() [Pointer notation]

#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 程序並將卡片(套裝,等級)的值存儲在相應的 arrays 中,但每次運行我的程序時都會出現分段錯誤。 我不確定我在哪里做錯了。 歡迎任何建議謝謝。

您的意思是為 52 個Card分配空間,但您為 52 個char分配了空間。 您分配 memory 的行應該是Card * deck = (Card *) malloc(DECK_SIZE * sizof(Card));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM