调整双指针数组C++大小

Resizing a C++ double pointer array

本文关键字:C++ 大小 数组 指针 调整      更新时间:2023-10-16

我正在尝试在C++中调整指针到指针数组的大小,但是在调整大小后遇到了分段错误。

我的调整大小代码如下所示:

CustomClass **arr;
int capacity = 20;
...
void resize(size_t new_capacity) {
CustomClass** resized_arr = new CustomClass*[new_capacity];
memcpy(resized_arr, arr, new_capacity * sizeof(CustomClass));
delete [] arr;
capacity = new_capacity;
arr = resized_arr;
print(); // segmentation fault while printing half way through the hash array
}
void print() {
for (int i = 0; i < capacity; i++) {
if (arr[i] != NULL) {
cout << "KEY: " << i << ", VAL: " << arr[i]->to_string() << endl; // the to_string() seg faults
}
}
}
string to_string() { return a + " of " + b; } // a and b are strings

print 函数将打印出数组中的一些项目,然后 seg 错误。

您在memcpy中复制了错误的字节数,并且新元素需要初始化为 NULL。 将现有的memcpy调用替换为以下语句:

memcpy(resized_arr, arr, capacity * sizeof(*resized_arr));
for (size_t c = capacity; c < new_capacity; ++c)
resized_arr[c] = nullptr;

capacitynew_capacity应该是相同的类型。 如果新容量可能小于旧容量,则需要进行调整。

或者,您可以使用新的for循环,而不是新的循环

memset(&resized_arr[capacity], 0, sizeof(*resized_arr) * (new_capacity - capacity));

但这更容易出错,如果新容量小于旧容量,则会出现问题。

您可以将内存替换为

for (size_t c = 0; c < capacity; ++c)
resized_arr[c] = arr[c];

以避免弄错memset的问题。 编译器在优化时,可能会以任何一种方式生成相同的代码。

这一行是错误的:

memcpy(resized_arr, arr, new_capacity * sizeof(CustomClass));

它应该是:

memcpy(resized_arr, arr, new_capacity * sizeof(CustomClass*));

请注意,您可以通过使用例如std::vector<CustomClass>std::vector<std::shared_ptr<CustomClass> >而不是原始数组来避免很多不必要的痛苦。

print()方法失败,因为当您创建新的CustomClass*指针数组时,您不会将其初始化为零,因此,打印时检查nullptr失败,并且您在无效指针上调用to_string()

所以第一件事是第一位的:

CustomClass** resized_arr = new CustomClass*[new_capacity](); 

注意()在最后,这将确保所有指针均为空。要将旧数组memcpy新数组,您需要知道要复制多少字节,这将是指针中的旧容量 * 字节CustomClass*,因此

memcpy(resized_arr, arr, capacity * sizeof(CustomClass*));

这是这种工作的示例: https://ideone.com/HStRBI