In general, there is a question. I make a single linked list. Naturally, this is a class and structure. In general, I saw others, the function of adding an item, write through a new Item, I just declare the Item. It seems to be debugging everything plows, but when I call the output function, the values ​​of the firstItem and lastItem pointer are lost ... Maybe someone can help? It seems that the usual declaration should also be allocated memory (Item itm;)

List.h

#pragma once class List { struct Item { int number; Item * next; }; int countAll; Item * firstItem = NULL; Item * lastItem = NULL; public: void AddLast(int); void RemoveLast(); void ShowAllElements(); void showItem(Item *); List(); ~List(); }; 

list.cpp

  #include "stdafx.h" #include "List.h" #include <iostream> using namespace std; void List::AddLast(int n) { Item itm = { n, NULL }; /*itm->next = NULL; itm->number = n;*/ if (firstItem == lastItem) { firstItem = &itm; lastItem = firstItem->next; } else { lastItem = &itm; lastItem->next = itm.next; lastItem = lastItem->next; } } void List::RemoveLast() { Item * tmp; tmp = lastItem->next; delete lastItem; lastItem = tmp; } void List::ShowAllElements() { Item *next = firstItem->next; Item *itm = firstItem; while (next) { showItem(itm); itm = itm->next; next = itm->next; } } void List::showItem(Item * itm) { cout << "there is number: " << itm->number << endl; } List::List() { Item itm; this->firstItem = this->lastItem = &itm; } List::~List() { } 

main

 // OneRootList.cpp: определяет точку входа для консольного приложения. // #include "stdafx.h" #include "List.h" #include <iostream> using namespace std; int main() { List list; list.AddLast(1); list.AddLast(1); list.ShowAllElements(); } 
  • "others, the function of adding an item, write through new Item, I just declare Item" - this is you in vain)) new - dynamic memory allocation. The allocated memory is saved even after the closure of the function. But, if you create an array without using dynamic memory allocation, the lifetime of this array is limited to its scope. Those. memory will be released immediately upon completion of the function. - Andrej Levkovitch

1 answer 1

 void List::AddLast(int n) { // создали ЛОКАЛЬНУЮ переменную Item itm = { n, NULL }; /* ... */ // присвоили её адрес... firstItem = &itm; // а вот тут локальня переменная itm уничтожается, и // firstItem теперь указывает в никуда } 

The same problem in the constructor. And at the same time, in the RemoveLast() method, you apply delete to memory, which is generally unclear what it is.

Findings:

  1. A new list item should be created via new
  2. Provide for the correct deletion of created elements in the destructor.