As I have just learned templates in C++, I started to practice it. I am at the beginning of the implementation of a Linked List using templates and I have been having an error on Xcode, where it states: "Thread 1: EXC_BAD_ACCESS(code=1, address=0x9)". In my other compiler, it says it is a segmentation fault, but I cannot find the cause of it. What might be the reason of this error?
#include <iostream>
using namespace std;
template <typename T> struct Node{
T value;
Node * ptr;
};
template <typename T> class LinkedList {
public:
LinkedList(const T & element);
T & push(const T & element);
T & pop(const int index);
int get_size() const { return this->_size; }
void printll();
private:
LinkedList(){};
struct Node<T> * head;
int _size;
};
template <typename T> LinkedList<T>::LinkedList(const T & element){
struct Node<T> new_node;
new_node.value = element;
new_node.ptr = nullptr;
this->head = &new_node;
this->_size = 1;
}
template <typename T> void LinkedList<T>::printll(){
if(this->head != nullptr){
Node<T> * temp = this->head;
while((*temp).ptr != nullptr){ // Error here.
cout << (*temp).value << " ";
temp = temp->ptr;
}
cout << (*temp).value << endl;
cout << endl;
}else {
cout << "The list is empty!" << endl;
}
}
int main(int argc, char** argv){
LinkedList<int> l1(5);
l1.printll();
return 0;
}
Aucun commentaire:
Enregistrer un commentaire