首页 > 解决方案 > 我在实现堆栈数据结构时遇到分段错误

问题描述

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

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

标签: csegmentation-faultstack

解决方案


我怀疑你想写这样的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如果您有任何其他疑问,请发表评论。我将编辑我的答案来回答这个问题。


推荐阅读