【发布时间】:2020-06-28 02:20:52
【问题描述】:
我在以下代码 sn-p 中遇到分段错误。它是一个代码,应该为交易卡中的各种属性分配值并显示它。我通常在数据结构方面搞砸了,所以如果你们可以推荐一些资源来了解分段错误和类似的东西,这将非常有帮助。
#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);
}
【问题讨论】:
-
player1变量永远不会被分配分配的内存,因为您将player1的副本传递给createStack,并且此函数将指针分配给局部变量,因此一旦函数丢失,它就会丢失返回。player1仍然是NULL因此是段错误。 -
要从
createStack修改player1,您需要传递其地址,或者更改createStack以返回新的头部并将其分配给调用者中的player1。跨度> -
非常感谢你们的意见。双 de 引用变量 head(即被传递的 player1)产生了所有的不同,因为函数得到了一个真正的参数来处理而不是一个副本。
标签: c segmentation-fault stack