Tayl
Tayl

Reputation: 49

Segmentation Fault after accessing node

I'm trying to make a random deck of cards using a linked list. However, whenever I try to use my addCard function I get a segmentation fault error.

Is temp->card->suit=suits; the proper way to change the value of a node inside a node? I think thats where my issue is.

Thanks!

struct Card{//card node
    char suit;
    int value;
};

struct BagNode{//bag node
    Card* card;
    BagNode *next;
};

class Bag{
  private:
    BagNode *head, *tail;
  public:
    int size;
    void addCard(char suits, int values){//adds card to end of deck
            BagNode *temp=new BagNode;
            temp->card->suit=suits;
            temp->card->value=values;
            temp->next=head;
            head=temp;
    }

};

int main(){
    Bag deck;
    deck.addCard('H',10);
}

Upvotes: 1

Views: 320

Answers (1)

Nick Reed
Nick Reed

Reputation: 5059

When you first create a new BagNode with BagNode *temp=new BagNode, you don't initialize the card or next member variables. Trying to access temp->card->suits causes a segfault because you're trying to access a member variable of card before the card itself is defined.

Try this:

BagNode *temp=new BagNode;
temp->card = new Card();
temp->card->suit=suits;
temp->card->value=values;
temp->next=head;
head=temp;

Upvotes: 1

Related Questions