c - 我在实现堆栈数据结构时遇到分段错误
问题描述
我在以下代码片段中遇到分段错误。它是一个代码,应该为交易卡中的各种属性分配值并显示它。我通常在数据结构方面搞砸了,所以如果你们可以建议一些资源来了解分段错误和类似的东西,这将非常有帮助。
#include<stdio.h>
#include<stdlib.h>
typedef struct cards
{
int power;
int energy;
int heal;
int karma;
struct cards *next;
}node;
node *createCards()
{
node *new_node=(node*)malloc(sizeof(node));
new_node->energy=500+rand()%400;
new_node->heal=100+rand()%200;
new_node->karma=50+rand()%100;
new_node->power=1000+rand()%501;
return new_node;
}
void createStack(node *head, int no_cards)
{
if(head==NULL)
head=createCards();
head->next=NULL;
int i=0;
while(i<no_cards-1)
{
node *tmp=createCards();
tmp->next=head;
head=tmp;
i++;
}
}
void displayCards(node *head)
{
node *crt=head;
int i=1;
while(crt->next)
{
printf("\n ------------------------------------- ");
printf("\n | <%d> |", i);
printf("\n | |");
printf("\n | POWER : %d |", crt->power);
printf("\n | |");
printf("\n | |");
printf("\n | ENERGY: %d |", crt->energy);
printf("\n | |");
printf("\n | |");
printf("\n | HEAL : %d |", crt->heal);
printf("\n | |");
printf("\n | |");
printf("\n | KARMA : %d |", crt->karma);
printf("\n | |");
printf("\n -------------------------------------");
i++;
crt=crt->next;
}
}
node *player1=NULL;
int main()
{
createStack(player1, 10);
displayCards(player1);
}
解决方案
我怀疑你想写这样的createStack()
函数
void createStack (node *head, int no_cards) {
if (head == NULL) {
head = createCards();
}
int i = 0;
node *tmp = head;
while(i < no_cards) {
tmp->next = createCards();
tmp = tmp->next;
i++;
}
}
我注意到您正在创建一个链表而不是堆栈。并删除crt->next
函数中 while 循环底部的行displayCards()
。谢谢你的提问:)
PS如果您有任何其他疑问,请发表评论。我将编辑我的答案来回答这个问题。
推荐阅读
- apostrophe-cms - 如何从 Apostrophe CMS 中的嵌套连接中检索信息?
- python - Python google cloud appengine requirements.txt 加载/python 文件不再工作
- curl - cURL - 在配置文件中使用 -d (POST)?
- machine-learning - keras.activations.softmax 和 keras.layers.Softmax 有什么区别?
- php - 如何将购物车中的多个产品作为单独的行插入数据库
- javascript - 我没有在客户端上实时看到带有节点 js 的 json 文件的值
- java - BeanUtils / PropertyUtils 读取嵌套的“集合”
- php - file_get_contents 在加载网页 5 秒后获取数据
- c# - 使用 Invalidate() Outlook Addin C# 清除下拉列表
- reactjs - 是否可以防止默认的onDeselect,(选择输入多个蚂蚁设计)?