删除数组指针? [英] Delete array pointer?
问题描述
如何删除已分配给数组models
,names
的内存?我尝试了每种方法,但运行时总是崩溃.
How do I delete the memory that have been allocated for array models
, names
? I tried every method but it always crashes when I run it.
int main()
{
vector<Person*> people;
const int PERSON_SZ = 4;
char * names[] = {"Jim", "Fred", "Harry", "Linda"};
int ages[] = { 23, 35, 52, 59 };
for (int i = 0; i < PERSON_SZ; i++)
{
Person * temp = new Person(names[i], ages[i]);
people.push_back(temp);
}
// A vector of Car pointers
vector<Car*> cars;
const int CAR_SZ = 3;
char * models[] = { "Festiva", "Ferrarri", "Prius" };
srand(time(0));
for (int i = 0; i < CAR_SZ; i++)
{
Car * temp = new Car(models[i]);
temp->set_driver(people[rand() % (people.size())]);
temp->set_owner(people[rand() % (people.size())]);
cars.push_back(temp);
}
for (int p = 0; p < people.size(); p++)
{
people[p]->increment_age();
}
for (int c = 0; c < cars.size(); c++)
{
cars[c]->print();
}
delete [] names;
for ( int r = 0; r < CAR_SZ; ++r )
{
delete [] models[r];
}
return 0;
}
推荐答案
您没有使用new
分配models
和names
,因此您无法delete
分配它们.
You didn't allocate models
and names
using new
, so you cannot delete
them.
这两个数组都分配在堆栈上,并在函数返回时自动删除.
Both arrays are allocated on the stack and are automatically deleted, when the function returns.
(字符串)数组的内容(即字符串本身)存储在全局数据段中,根本无法释放.这也很危险,因为编译器可能在程序的不同位置使用相同的字符串常量.
The contents of the (string) arrays (i.e. the strings itselves) are stored in the global data segment and cannot be freed at all. This would also be dangerous because the compiler might use the same string constant at different places in the program.
这篇关于删除数组指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!