что случилось с моим кодом? - PullRequest
1 голос
/ 27 февраля 2011

Я новичок в C ++. Я действительно запутался между C и C ++. Я знаком с C и Java, но не C ++. Сегодня я собираюсь написать программу со связанным списком, используя C ++. Но что случилось с моим кодом ??? Спасибо.

Raymond

результат: Необработанное исключение в 0x00412656 в 09550978d.exe: 0xC0000005: Место записи нарушения прав доступа 0xcdcdcdcd.

#include <iostream>
#include <string> 
using namespace std;

struct word
{

    bool empty;
    string name;
    int count;
    word* next;
};
typedef struct word word;

word* create(word* theList)
{
    word* head = (word*)malloc(sizeof(word));
    head->empty = false;
    head->name = "";
    head->next = 0;
    return head;
}

void print(word* theList)
{
    word* current = theList;
    while(current!=0)
    {   cout << current->name << " : " << current->count << " \n" ;
        current = current->next;
    }

}

void add(string myString, word* theList)
{
    //word* newWord = (word*)malloc(sizeof(word));
    if( theList->empty == false )
    {
        theList->empty = true;
        theList->name = myString;
        theList->next = 0;
    }
    else
    {
        word* current = theList;
        while(current->next!=0)
        {
            current = current->next;
        }
        word* newWord = (word*)malloc(sizeof(word));
        newWord->empty = true;
        newWord->name = myString;
        newWord->next = 0;
        current->next = newWord;
    }
}

int main(void)
{
    word* theList = 0;
    theList = create(theList);
    add("Hello", theList);
    //add("world", theList);

}





















#include <iostream>
#include <string>
using namespace std;


class word
{
public:
    string name;
    int count;
    word *next;

word (string name);

};



word::word (string myName)
{
    name = myName;
    next = NULL;
    count = 1;
}

class List
{
public:
    bool isEmpty;
    word* theHead;



List();
List(word* aHead);
void print();
void add(string myString);
void search(string myString);
};



List::List()
{
    isEmpty = true;
}



List::List(word* aHead)
{
    isEmpty = false;
    theHead = aHead;
}



void List::add(string myString)
{
    word* newWord = new word(myString);
    if (isEmpty == true)
    {
        isEmpty = false;
        theHead = newWord;
    }
    else
    {
        word* current = theHead;
        if ( current->next == NULL)
        {
            if( myString.compare(current->name) == 0 )
            {
                current->count = current->count + 1;
                return;
            }
        }
        else
        {
            while ( current->next != NULL )
            {
                if( myString.compare(current->name) == 0 )
                {
                    current->count = current->count + 1;
                    return;
                }
                current = current->next;
            }
        }
        current->next = newWord;
    }
}
void List::print ()
{
    if (isEmpty)
    {
        cout << "nothing in the list";
    }
    else
    {
        word* current = theHead;
        while(current !=  NULL)
        {
        cout << current->name << " : " << current->count << " \n" ;
        current = current->next;
        }
    }
}

void List::search(string myString)
{
    if (isEmpty)
    {
        cout << "The word : " << myString << " is not in the List.\n";
    }
    else
    {
        word* current = theHead;
        while( current != NULL )
        {
            if( myString.compare(current->name) == 0 )
            {
                cout << "The word : " << myString << " is in the List.\n";
                return;
            }
            else
            {
                current = current->next;
            }
        }

        cout << "The word : " << myString << " is not in the List.\n";
    }
    return;
}


int main(void)
{
    List theList = List();
    string str1 = "Hello";
    string str2 = "world";
    theList.add(str1);
    theList.add(str2);
    theList.add(str1);
    theList.search("Hello");
    theList.search("You");

    theList.print();
    int i;
    scanf("%d", &i);
}

Ответы [ 3 ]

3 голосов
/ 27 февраля 2011

Наиболее очевидная проблема: используйте new, а не malloc для размещения новых объектов: malloc не вызывает конструктор, и один принцип разработки C ++ состоит в том, что конструкторы вызываются перед любыми другими операциями над объектом.

Кстати, ваш код выглядит как C, используя только самые основные функции C ++. Это никогда не будет написано кем-то, знающим C ++ (слово будет иметь конструктор и закрытый член, даже для людей, использующих C ++ в качестве «лучшего C»).

3 голосов
/ 27 февраля 2011

Вы должны использовать оператор new вместо malloc.Смотрите разницу здесь .Кроме того, зачем использовать struct s и typedef s, когда c ++ позволяет вам сделать class

Вот моя версия вашего кода, она еще не содержит ошибок, но она должна проиллюстрировать, как использовать new и classes.Я постараюсь исправить это полностью и обновить вас.

Также обратите внимание, что в структуре класса c ++ вы автоматически получаете указатель this с функциями-членами, который действует как указатель на класс, так что вы больше не будетедолжен передать word* theList

Редактировать: я обновил с рабочим кодом, единственное, что не работает, это аспект подсчета в списке.В противном случае обратите внимание, что есть два класса, List интерфейсы с word для создания связанного списка, я не включил в код какие-либо аспекты управления памятью (что было бы не так сложно при использовании деструктора c ++, если вам нужны такие средствапожалуйста, укажите это в комментариях, и я обязательно добавлю.

#include &#60;iostream&#62;
#include &#60;string&#62;
using namespace std;</p>

<p>class word
{
public:
    string name;
    int count;
    word *next;</p>

<pre><code>word (string name);

};

word :: word (string myName) {name = myName; next =NULL; count = 0;}

список классов {public: bool isEmpty; word * theHead;

List();
List(word* aHead);
void print();
void add(string myString);

};

List :: List () {isEmpty= true;}

List :: List (word * aHead) {isEmpty = false; theHead = aHead;} ​​

void List :: add (string myString) {word * newWord = newword (myString); if (isEmpty == true) {isEmpty = false; theHead = newWord;} else {word * current = theHead; while (current-> next! = NULL) {current = current-> next;} current-> next = newWord;}} void List :: print () {if (isEmpty) {cout << "ничего в списке";} else {word * current = theHead; while (current! =NULL) {cout << current-> name << ":" << current-> count << "\ n";текущий = текущий-> следующий;}}}

int main (void) {List theList = List ();string str1 = "Hello";строка str2 = "мир";theList.add (str1);theList.add (str2);theList.print ();}

Редактировать: Здесь деструктор для освобождения выделенной памяти, обязательно добавьте прототип ~List() в объявлении класса:

<code>List::~List()
{
    if (!isEmpty)
    {
        word* prev = NULL;
        word* current = theHead;
        while(current !=  NULL)
        {
            prev = current;
            current = current->next;
            delete prev;
        }
    }
}

Надеюсь, это поможет.

1 голос
/ 27 февраля 2011

Например, в функции Add

if( theList->empty == false )
 {
     theList->empty = true;
     theList->name = myString;
     theList->next = 0;
 }

должно быть противоположным - если list-> empty == true, тогда установите его в false.простой пошаговый 5-минутный сеанс отладки поможет вам найти ваши ошибки, а также заставит вас полюбить и использовать отладчик.Я серьезно. ПЫТАЙТЕСЬ ОТЛАДАТЬ !!!

my2c

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...