I have a question whether to free memory, I created a dynamic array Name? Thank you for understanding.

List.h

#include <iostream> #pragma once struct Listnode { char *name; int age; Listnode *next; Listnode(char *Name, int Age, Listnode *Next) :name(Name), age(Age), next(Next) {} }; class List { Listnode *head = nullptr; public: void push(char *name, int age); void show(); }; 

List.ccp

 #include "List.h" //добавление в начало. void List::push(char *name, int age) { if (head == NULL) head = new Listnode(name, age, head); else head = new Listnode(name, age, head); } void List::show() { Listnode *ptr = head; while (ptr) { std::cout << ptr->name << ' ' << ptr->age << std::endl; ptr = ptr->next; } } 

Main.ccp

 #include <iostream> #include "List.h" int menu(); void enter(List &a); void show(List &a); int main() { setlocale(NULL, "RUS"); List A; char choice; for (;;) { choice = menu(); switch (choice) { case 'e': { enter(A); break; } case 's': { show(A); break; } case 'q': return 0; } } } int menu() { char ch; do { std::cout << "(E)nter of data\n"; std::cout << "(S)how of data\n"; std::cout << "(Q)uit\n"; std::cin >> ch; } while (!strchr("esq", tolower(ch))); return tolower(ch); } void enter(List &a) { char name[30]; std::cout << "Введите имя: "; std::cin >> name; char *Name = new char[strlen(name) + 1]; strcpy(Name, name); int age; std::cout << "Введите возраст: "; std::cin >> age; a.push(Name, age); } void show(List &a) { a.show(); } 

    1 answer 1

    If you mean if you need to delete the Name dynamic array in the enter function, then no, you do not need it, since you enter pointer to this array into the list node.

    Another thing is that you should write a destructor of the list, which will delete all nodes, including memory, addressed by pointers that are defined in nodes.

    • Thanks, understood a little. Another question I can write a function that will, for example, sort by int or by char - Ilya
    • @Ilya Why not? - Vlad from Moscow
    • From the point of view of correctness, did I write the code correctly or can I write somewhere else? - Ilya
    • instead of enter wrote nteer I understand you correctly? - Ilya
    • @Ilya This is a typo. - Vlad from Moscow