“init_deck”方法返回错误:从类型struct * Card分配类型struct Card时出现不兼容的类型 (* p ++ = card_create(rank [k],suit [j]))
我不确定这意味着什么,或者如何解决这个问题。如果有人能够解释这在装配级实际上做了什么以及它如何与C相对应,那将非常感激。
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
int main(int argc, char *argv[]){
struct Card{
int value;
char* suit;
};
struct Card *card_create(int value, char* suit){
struct Card *theCard = malloc(sizeof(struct Card));
assert(theCard != NULL);
theCard->value = value;
theCard->suit = strdup(suit);
return theCard;
}
void card_destroy(struct Card *theCard){
assert(theCard != NULL);
free(theCard->suit);
free(theCard);
}
void setValue(struct Card *theCard, int value){
theCard->value = value;
}
int getValue(struct Card *theCard){
return theCard->value;
}
char* getSuit(struct Card *theCard){
return theCard->suit;
}
void card_print(struct Card *theCard){
printf("%i of %s\n", getValue(theCard), getSuit(theCard));
}
void init_deck(struct Card deck[52]){
struct Card *p = deck;
char *suits[] = {"Hearts", "Diamonds", "Clubs", "Spades"};
int rank[] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 74, 81, 75, 65} //Last 4 numbers are int rep of char: J, Q, K, A
int j = 0, k = 0;
for(; j < 4; j++)
for(; k < 13; k++)
(*p++ = card_create(rank[k], suits[j]));
}
}
答案 0 :(得分:2)
card_create
返回指针,但*p
不是指针。 (不同类型)
(1)
替换
*p++ = card_create(rank[k], suits[j])
与
struct Card *aCard = card_create(rank[k], suits[j]);
*p++ = *aCard;
card_destroy(aCard);
(2)card_create non use malloc version
struct Card card_create(int value, char* suit){
struct Card theCard;
theCard.value = value;
theCard.suit = strdup(suit);//Since you are using a string literal Strdup it is not required. just theCard.suit = suit;
return theCard;
}
...
*p++ = card_create(rank[k], suits[j])
答案 1 :(得分:1)
您的deck
应该是卡**而不是卡*。
card_create
的结果是Card*
,您尝试使用指针Card
放入*p
stuct。