gpt4 book ai didi

c - 不兼容的类型分配

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

“init_deck”方法返回错误:从类型 struct * Card 分配给类型 struct Card 时,类型不兼容 (*p++ = card_create(等级[k], 套装[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]));
}
}

最佳答案

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不使用malloc版本

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])

关于c - 不兼容的类型分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34744248/

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