C ++使用delete []删除结构数组 [英] C++ Deleting array of structures with delete[]
问题描述
我在向cpp中的数组添加结构时遇到麻烦.我想出了这种方法,该方法在ints上很好用,但是当我想在结构上做同样的事情时,添加3个或更多后会报错.我对其进行了一点调试,似乎delete []导致了错误消息分段错误(内核已转储)".我不能使用向量或stl中的列表,所以不要建议这是一些代码:
I'm having trouble with adding structures to array in cpp. I've came up with this method which works great on ints but when i want to do the same thing on structures im getting error after adding 3 or more. I debugged it a little bit and it seems that delete[] is causing error message "Segmentation fault (core dumped)". I cant use vectors or list from stl so dont suggest that Here's some code:
struct sth
{
unsigned int id;
std::string name;
};
unsigned int id_counter = 0;
unsigned int counter_int = 0;
sth *array = new sth[0];
void print_array()
{
for (int i = 0; i < counter_int; ++i)
{
std::cout << array[i].id << ' ' << array[i].name << " -- ";
}
std::cout << '\n';
}
void add_sth(sth value)
{
sth *newArr = new sth[counter_int + 1];
memcpy(newArr, array, counter_int * sizeof(sth));
delete[] array;
array = newArr;
array[counter_int] = value;
++id_counter;
++counter_int;
}
int main(int argc, char const *argv[])
{
sth e1 = {1, "abc1"};
sth e2 = {2, "abc2"};
add_sth(e1);
add_sth(e2);
add_sth(e2);
print_array();
}
推荐答案
问题可能是试图使用memcpy复制 std :: string
.
The problem is probably trying to copy an std::string
with memcpy.
std :: string
不是POD(普通旧数据)对象,某些编译器和当然是静态代码分析器,例如SonarQube或Klocwork会提醒您你在做什么错了.
std::string
is not a POD (Plain Old Data) object, and some compilers and
certainly static code analyzers e.g. SonarQube or Klocwork will alert you that
what you are doing is wrong.
要正确完成复制,您应该定义一个赋值运算符,然后逐一复制项目,或仅使用动态容器,例如 std :: vector
To accomplish a copy correctly you should define an assignment operator and
copy the items one by one, or just use a dynamic container e.g. std::vector
这篇关于C ++使用delete []删除结构数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!