2013-08-17 2 views
0

언어에 대한 이해를 높이기 위해 C++에서 단독으로 연결된 목록 클래스를 작성 중이며 벽에 부딪혔습니다.0xC00000005 인스턴스화되지 않은 포인터 포인터 오류

제목은, 슬프게도, 내가 오류로 알아낼 수있는 거의 모든 것입니다. herehere 둘 다 구현하기 위해 노력하지 않은 일부 답변을 제시하는 것 같습니다.

MAIN.CPP :

#include <iostream> 
#include <string> 
#include "LinkedList.h" 
#include "Node.h" 

using namespace std; 

int main() 
{ 
    LinkedList<string> moo2; 
    moo2.insertAtFront("one"); 
    moo2.insertAtFront("two"); 
    moo2.insertAtFront("three"); 
    moo2.insertAtFront("four"); 
    cout<<moo2.toString() << endl; 

    cin.ignore(1); 
    return 0; 
} 

LinkedList.h :

#pragma once 
#include "Node.h" 
#include <string> 
#include <sstream> 

template <class type> 
class LinkedList 
{ 
private: 
    int size; 
    node<type> *head; 

public: 
    LinkedList() 
    { 
     head = NULL; 
     //head = (node<type>*)malloc(sizeof(node<type>)); 
     size = 0; 
    } 
    /*LinkedList(const LinkedList<type> &x) 
    { 
     head = NULL; 
     //head = (node<U>*)malloc(sizeof(node<U>)); 
     size = 0; 
    }*/ 

    bool insertAtFront(type obj) 
    { 
     node<type> *temp; 
     temp = (node<type>*)malloc(sizeof(node<type>)); 
     temp->data = obj; 
     temp->next = head; 
     head = temp; 

     size++; 
     return true; 
    } 

    std::string toString() 
    { 
     std::stringstream value; 
     node<type> *i = head; 
     while(i != NULL) 
     { 
      value << i->data; 
      if(i->next != NULL) 
       value << ", "; 
      i = i->next; 
     } 
     return value.str(); 
    } 
}; 

node.h : (어쨌든 어떤 확신을 가지고,) 나는 아무 생각이

#pragma once 
#include <string> 

template <class type> 
struct node 
{ 
    type data; 
    node *next; 

    node() 
    { 
     data = NULL; 
     next = NULL; 
     //data = new type(); 
     //next = (node<U>*)malloc(sizeof(node<U>)); 
    } 
    node(type) 
    { 
     data = type; 
     next = NULL; 
     //next = (node<U>*)malloc(sizeof(node<U>)); 
    } 
    node(type, node *) 
    { 
     data = type; 
     next = next2; 
    } 
    /*node(const node &x) 
    { 
     data = new type(x->data); 
     next = new x->next; 
    }*/ 
}; 

변수 LinkedList의 * head (또는 head-> data 또는 head-> next) 또는 노드 * next가 될 수 있으므로 오류가 발생합니다.

정말 이상한데, 지금까지 (int, double, long, char, char *) 시도한 다른 매개 변수화 된 형식의 코드는 완벽하게 작동합니다. 실제로 char *를 사용하여 문자열 목록과 동일한 목표를 달성 할 수도 있습니다. 그래도 문제가있는 이유와 해결 방법을 알고 싶습니다.

+6

'malloc'을'new'로 바꾸는 것으로 시작하십시오. – chris

+0

나는 chris의 의견을 수천 배로 늘릴 수 있었으면 좋겠다. 당신은 당신의'node' 생성자 중 * none *이 (그리고 그들의 멤버 초기화가) 실행되고 있다는 것을 알지 못합니까? – WhozCraig

+0

또한 깨졌습니다 : main24.cpp : 생성자 '노드 :: 노드 (유형)': main24.cpp : 19 : 20 : 오류 : ';'토큰 앞에 예상 주 표현식 data = type; – lpapp

답변

3

malloc 대신 new을 사용하십시오.

malloc은 주어진 유형이나 크기에 대해 메모리를 할당하기 만하며 생성자를 호출하지 않습니다.

+0

감사합니다. – headlessgargoyle