Almost right :) Now I will explain why "almost."
In C ++, every object has the same thing as a constructor and destructor. If you don’t write them yourself, the compiler will generate them (everything is a bit more complicated, but I simplify as much as I can). The destructor is called when the object is destroyed, so here
delete []pCar;
he will be called. But you did not write your destructor, and the generated one has no idea what to do with the name and therefore does not do anything. So you need to add your destructor -
struct car { char *name; ~car() { delete[]name; } };
In this case, it will be enough to write your delete []pCar; - and everything will be correct. Nearly. Why almost? because what if you forget to initialize the name ? And it will show incomprehensibly where, and when deleting it is unclear what can happen, anything. Therefore, let's add a constructor
car(): name(nullptr) {}
And everything would be fine, but someone can (maybe even you) write somewhere pCar->name = "ПЦ" . And when you try to release will be trouble. Therefore, it is better to do not a structure, but a class:
struct car { public: car(): name(nullptr) {} ~car() { delete[]name; } private: char *name; };
Is it done? Nearly. Because you need to somehow somehow force name to store the string. Again, we do the constructor
car(const char * str):name(nullptr) { if (str) { name = new char[strlen(str)+1]; strcpy(name,str); } }
and the member function to access this line:
const char* str() const { return name; }
and the assignment operator to change the name :
car& operator=(const char * str) { delete[]name; if (str) { name = new char[strlen(str)+1]; strcpy(name,str); } else name = nullptr; }
Now it can be considered ready. Much more can be added, but the main thing is already in place:
struct car { public: car(const char * str = nullptr):name(nullptr) { if (str) { name = new char[strlen(str)+1]; strcpy(name,str); } } ~car() { delete[]name; } const char str() const { return name; } car& operator=(const char * str) { delete[]name; if (str) { name = new char[strlen(str)+1]; strcpy(name,str); } else name = nullptr; } private: char *name; };
And your code turns into
car *pCar = new car[QCar]; for ( int i = 0; i < QCar; i++) { cout << "Car name: "; char temp [size_m]; char >> temp; pCar[i] = temp; } cout << " Your auto"<< endl; for ( int i = 0; i < QCar; i++) { cout << pCar[i].str(); } delete []pCar;
Something like this - but only for a start :)