首页 > 解决方案 > c函数将完整的卡片组存储到动态链接的数组中

问题描述

我想做一个存储完整卡片组的函数,如下所示:

以此类推,动态链表中每个节点只有一张卡。这是我尝试过的,但它不起作用。请注意,套牌存储在 .txt 文件中。

void make_list(deck[52][3])
    {
        typedef struct cards
            {
                char card[3];
                struct cards *next;
            } cards_t;

        int j;

        cards_t *head = NULL; //initialization
        head = (cards_t*) malloc (sizeof(cards_t));

        for (j=0; j<52; j++)
            {
                head-> card[3] = deck[j][3];
                head->(next + j) = (cards_t*) malloc(sizeof(cards_t)); 
            } 

我几乎是一个初学者,因此非常感谢任何对我的错误或解决方案的详细解释:)

标签: carrayslinked-list

解决方案


我看到代码存在一些高级问题。

  1. 当您有一个双字符指针(甲板)时,您将访问单个字符,deck[x][y]但如果您想要整个字符,AS那么您只需要deck[x].
  2. 你的for循环每次都在改变 head 的值,它没有列出一个列表。在 for 循环结束时,唯一更改的值将是 head 和 next。这也将导致大量内存泄漏,因为您 malloc 一个新的struct cards但在下一次迭代中立即丢失了它的地址。
  3. 您的访问权限head->card[3] = deck[j][3]无效。[3]附在卡上是无效的,应该只是head->card = deck[j]
  4. 链接列表不像您在 (next + j) 中尝试过的那样工作。那将更适合数组。对于列表,您必须在列表中导航以添加一个节点(或者可能有一个指向列表末尾的指针)。
  5. 您的方法返回是无效的,但是由于您在方法中定义了整个列表,它可能应该返回节点的头部,以便所有数据都可以从方法外部获得。同样重要的是要注意,如果deck变量超出范围,则列表将指向垃圾数据,因为它可能会在内存中被覆盖。如果您想避免这种情况,您需要确保套牌不会超出范围,或者为每张卡做一个memcpyor 。strcpy

如果你想初始化卡片的链接列表,它会更像

typedef struct cards //Should be done outside of function
{
  char card[3]; //2 characters + '\0'
  struct cards * next;
} cards_t;

cards_t * make_list(char ** deck) //Assuming deck is double character array as you showed it
{
   //Initialize values
   int j = 0;
   cards_t *head = malloc (sizeof(cards_t)); //Note it isn't required to cast from malloc

   //Iterate over the deck and append to the linked list
   //here, we will start our variable at the head of the list. We will repeat 
   //this iteration 53 times and after each iteration, 
   //the variable will move onto the next node of the linked list.
   for (cards_t * iterator = head; j<52; iterator = iterator->next, j++)
   {
      iterator->card = deck[j]; //This will store the 3 card character name
      iterator->next = malloc(sizeof(cards_t)); 
   }//for

   return head;
}//make_list

推荐阅读