如何访问指向struct的指针的成员?

时间:2019-04-09 04:13:33

标签: c arrays memory-management struct

我试图使指针和C变得更舒适,所以我一直在练习问题。我有一个结构:

typedef struct Card
{
    enum { hearts, spades, clubs, diamonds } suit;
    int value;
} Card;

和用于为卡座分配内存的函数:

void createDeck(Card ** deck)
{
    deck = malloc(52 * sizeof(Card *)); //allocate space for deck
    if (deck == NULL)
    {
        fprintf(stderr, "malloc failed\n");
        return;
    }

        //allocate memory for each card in deck
    for (size_t i = 0; i < 52; i++)
    {
        *(deck + i) = malloc(sizeof(Card));
    }
}

并且我正在尝试使用如下代码:

int main()
{
    Card *deck = NULL;

    createDeck(&deck);

    printf("%d", deck[0].suit)
}

这给出了nullptr错误,这使我认为我没有正确分配内存。我已经更改了不同的内容,但是无论如何我都无法正常工作。使用deck完成对createDeck的成员访问后,如何访问它?

2 个答案:

答案 0 :(得分:3)

让我解决您的问题。

main()中,Card *deck = NULL;将分配一个指向Card的指针,并且该指针指向NULL。

然后调用createDeck(&deck);,您将在此处传递指向Card类型的指针的地址。因此,此地址不是NULL,因为它指向在Card *类型的堆栈上分配的指针变量。

这意味着在createDeck()中,变量deck将不为NULL,并且将具有有效地址。但是将指向类型为*deck的指针的Card*将为NULL。您应该只为*deck分配内存。

void createDeck(Card ** deck)
{
    //deck = malloc(52 * sizeof(Card *)); //deck is a double pointer pointing to memory of type Card* allocated on stack in calling function main().
    if (deck == NULL)
    {
        fprintf(stderr, "Null pointer error\n"); //If calling function passes NULL, it means there is some issue.
        return;
    }
    *deck = NULL; //In more complex functions, if there are other logic before doing malloc(), it it better to reset the variables with default values.

        //allocate memory for each card in deck
    //for (size_t i = 0; i < 52; i++)
    //{
    //    *(deck + i) = malloc(sizeof(Card));
    //}

    *deck = malloc(sizeof(Card)*52); //Allocate for all 52 Cards together
    if(NULL == *deck)
    {
        fprintf(stderr, "malloc failed\n");
        return;
    }

    //In case you want to access a card using deck variable.
    (*deck)[2].suit = hearts;
}

答案 1 :(得分:0)

如果没有double pointers,生活将会更加简单,据我所知,您需要arry的卡片(52)??

为什么不呢?

Card* createDeck( )
{
    Card *deck = malloc( 52 * sizeof(Card) );
    {
         printf("OOPS");
    }

    return deck;
}

和呼叫者

Card *deck = createDeck();
if( !deck )
{
   printf("Alloc Failure");
   exit(0);
}

或者更好地摆脱createDeck并直接致电malloc

Card *deck = malloc( 52 *  sizeof(Card));

如果您想以不同的方式看待事物,那就是完全不同的主张 例如,甲板是纸牌的集合

/* That's how a card looks like */
struct Card{
    int value;
    /* waharever else */
};

/* That's a deck */
struct deck {
   struct Card *cards;
};

现在初始化甲板

struct deck *createDeck( )
{
     struct deck *deck = malloc( struct deck );
     if( deck )
     {
         deck->cards = malloc( 52 * sizeof(card));
         if(deck->cards)
         {
            /* Do some thing or leavel it as is */
         }
     }

     return deck;
}

和呼叫者..

struct *deck = createDeck();
if( !deck )
{
    printf("OOps memory");
    exit(0);
}