c - c函数将完整的卡片组存储到动态链接的数组中
问题描述
我想做一个存储完整卡片组的函数,如下所示:
- AS 2S 3S 4S 5S 6S 7S 8S 9S TS JS QS KS...
以此类推,动态链表中每个节点只有一张卡。这是我尝试过的,但它不起作用。请注意,套牌存储在 .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));
}
我几乎是一个初学者,因此非常感谢任何对我的错误或解决方案的详细解释:)
解决方案
我看到代码存在一些高级问题。
- 当您有一个双字符指针(甲板)时,您将访问单个字符,
deck[x][y]
但如果您想要整个字符,AS
那么您只需要deck[x]
. - 你的
for
循环每次都在改变 head 的值,它没有列出一个列表。在 for 循环结束时,唯一更改的值将是 head 和 next。这也将导致大量内存泄漏,因为您 malloc 一个新的struct cards
但在下一次迭代中立即丢失了它的地址。 - 您的访问权限
head->card[3] = deck[j][3]
无效。[3]
附在卡上是无效的,应该只是head->card = deck[j]
。 - 链接列表不像您在 (next + j) 中尝试过的那样工作。那将更适合数组。对于列表,您必须在列表中导航以添加一个节点(或者可能有一个指向列表末尾的指针)。
- 您的方法返回是无效的,但是由于您在方法中定义了整个列表,它可能应该返回节点的头部,以便所有数据都可以从方法外部获得。同样重要的是要注意,如果
deck
变量超出范围,则列表将指向垃圾数据,因为它可能会在内存中被覆盖。如果您想避免这种情况,您需要确保套牌不会超出范围,或者为每张卡做一个memcpy
or 。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
推荐阅读
- python - Python 套接字异常处理在第一次迭代中不会引发错误
- r - 以编程方式调整 RStudio 控制台宽度
- python - 如何根据决策(布尔)字段在现有表单的视图中设置默认值?
- python - 使用 lambda 对字典的元素进行排序
- node.js - 运行多个 nodeJS 应用程序
- java - Spring Boot 404 调用尝试浏览到休息控制器时
- swift - 在 swift 4.2 中从数组返回组
- postgresql - 在 Postgres sql 两个表中反向相交
- c# - 在字符串位和字符串字符之间转换为 ASCII
- javascript - JS 如何处理回文