I'm trying to initiate an element inside a Node struct but whenever I try to access it I get a Segmentation Fault. I have initialized the Node inside my Stack class but cannot insert an element on it.
Stack.h
#ifndef QUEUE_H
#define QUEUE_H
struct Node;
// Pilha de números inteiros.
class Stack {
public:
// Representa uma exceção que ocorre quando a pilha está vazia.
class EmptyException {};
// Constrói uma pilha vazia.
Stack();
// Insere um elemento no topo da pilha.
void push(unsigned elem);
// Retorna o elemento no topo da pilha.
// Lança EmptyException caso a pilha esteja vazia.
unsigned top() const;
// Remove o elemento no topo da pilha.
// Lança EmptyException caso a pilha esteja vazia.
void pop();
// Retorna o número de elementos na pilha.
unsigned count() const;
private:
Node* _top{};
unsigned _count;
};
#endif
Stack.cpp - The segmentation fault is occurring on line 10
#include "Stack.h"
struct Node {
unsigned elem{};
Node * next{};
};
Stack::Stack() {
this->_count = 0;
this->_top->elem = 0; // This is where the segmentation fault is occurring
}
void Stack::push(unsigned elem) {
this->_top->elem = elem;
this->_count++;
}
void Stack::pop() {
// TODO.
}
unsigned Stack::top() const {
return 0;
}
unsigned Stack::count() const {
return 0; // TODO.
}