строка — ошибка C ++: необработанное исключение в 0x00934ABB (связанный список, адресная книга)

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

cin >> ch;
switch(ch)
{
case '1':
system("cls");
cout << "\n\nINSERT RECORD";
cout << "\n\nInput FIRST NAME: ";
cin.ignore();
getline(cin,firstname,'\n');
cout << "\n\nInput LAST NAME: ";
getline(cin,lastname,'\n');
cout << "\n\nInput PHONE NUMBER: ";
getline(cin,phonenumber,'\n');
cout << "\n\nInput DAY OF BIRTH: ";
getline(cin,dayofbirth,'\n');
cout << "\n\nInput MONTH OF BIRTH: ";
getline(cin,monthofbirth,'\n');
cout << "\n\nInput YEAR OF BIRTH: ";
getline(cin,yearofbirth,'\n');
cout << "\n\nInput AGE: ";
getline(cin,age,'\n');
cout << "\n\nInput STREET NAME (Address): ";
getline(cin,streetname,'\n');
cout << "\n\nInput CITY (Address): ";
getline(cin,city,'\n');
cout << "\n\nInput STATE (Address): ";
getline(cin,state,'\n');
cout << "\n\nInput ZIP CODE (Address): ";
getline(cin,zipcode,'\n');
cout << "\nRecord inserted!";
current = ad.AddNode(temp);
ad.userPromptStatement();
break;node* AddressBook::AddNode(nodePtr temp)
{
string firstname;
string lastname;
string phonenumber;
string dayofbirth;
string monthofbirth;
string yearofbirth;
string age;
string streetname;
string city;
string state;
string zipcode;
AddressBook ad;

if(head != NULL)
{
current = head;
while(current -> next != NULL)
{
current = current -> next;
}
current = new node;
current -> next -> firstname = temp -> firstname;
current -> next -> lastname = temp -> lastname;
current -> next -> phonenumber = temp -> phonenumber;
current -> next -> dayofbirth = temp -> dayofbirth;
current -> next -> monthofbirth = temp -> monthofbirth;
current -> next -> yearofbirth = temp -> yearofbirth;
current -> next -> age = temp -> age;
current -> next -> streetname = temp -> streetname;
current -> next -> city = temp -> city;
current -> next -> state = temp -> state;
current -> next -> zipcode = temp -> zipcode;
current -> next = nullptr;
return current;
ad.userPromptStatement();
}
else
{
head = new node;
head -> firstname = temp -> firstname;
head -> lastname = temp -> lastname;
head -> phonenumber = temp -> phonenumber;
head -> dayofbirth = temp -> dayofbirth;
head -> monthofbirth = temp -> monthofbirth;
head -> yearofbirth = temp -> yearofbirth;
head -> age = temp -> age;
head -> streetname = temp -> streetname;
head -> city = temp -> city;
head -> state = temp -> state;
head -> zipcode = temp -> zipcode;
head -> next = nullptr;
return current;
}
}

Я продолжаю получать ошибку в «xstring».

Когда я создаю 1 запись, ошибка не происходит, но когда я создаю вторую, я получаю это:
«Необработанное исключение в 0x00934ABB в dummy3.exe: 0xC0000005: Место чтения нарушения доступа 0xCDCDCDE5.»

bool _Grow(size_type _Newsize,
bool _Trim = false)
{   // ensure buffer is big enough, trim to size if _Trim is true
if (max_size() < _Newsize)
_Xlen();    // result too long
if (this->_Myres < _Newsize) /*** <- next statement that will be executed points to this line ***/
_Copy(_Newsize, this->_Mysize); // reallocate to grow
else if (_Trim && _Newsize < this->_BUF_SIZE)
_Tidy(true, // copy and deallocate if trimming to small string
_Newsize < this->_Mysize ? _Newsize : this->_Mysize);
else if (_Newsize == 0)
_Eos(0);    // new size is zero, just null terminate
return (0 < _Newsize);  // return true only if more work to do
}

есть идеи? Я ничего не знаю о части «xstring» ..

0

Решение

Ваша проблема лежит здесь:

current = new node;
current -> next -> firstname = temp -> firstname;

Вы только что создали новый узел (заменив текущий), а затем пытаетесь получить доступ к его дочернему (следующему), который не инициализирован.

Это должно быть лучше:

current -> next = new node;
current -> next -> firstname = temp -> firstname;
...
current -> next -> next = nullptr;
return current -> next;

Еще один совет: если tmp создается динамически, подумайте об использовании его напрямую, а не о копировании его элементов. Как это:

current -> next = tmp;

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

1

Другие решения

Вероятно, причиной этой ошибки является попытка доступа к нулевому указателю.

Вы должны создать температура прежде чем использовать его. Я не мог видеть любой указатель, имя которого является временным. Пожалуйста, сначала создайте temp и разместите его в памяти с помощью malloc или memset. Тогда вы можете передать ошибку.

0

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector