繁体   English   中英

实现堆栈数据结构时出现分段错误

[英]I am Getting segmentation fault while implementing Stack Data Structure

我在以下代码片段中遇到分段错误。 它是应该为交易卡中的各种属性赋值并显示它的代码。 我经常搞砸数据结构,所以如果你们可以推荐一些资源来了解分段错误和类似的东西,这将是非常有帮助的。

#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++;
    }
}

我注意到您正在创建一个链表而不是一个堆栈。 并删除函数displayCards() while 循环底部的crt->next行。 谢谢提问:)

PS如果您有任何其他疑问,请发表评论。 我将编辑我的答案来回答这个问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM