调整双指针数组C++大小
Resizing a C++ double pointer array
我正在尝试在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;
capacity
和new_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
相关文章:
- C++字符*缓冲区的大小
- 在C++中手动调整数组大小
- 用C++20 fmt限制结果的总大小
- 如何加载(或映射)文件部分的最大大小,但适合在Windows上的RAM
- 在UNIX系统中使用DIR查找文件的字节大小
- 调整大小后指向元素值的指针unordered_map有效?
- C++数组传递给大小为的函数
- 具有最大子序列大小的序列,每个元素都相同
- Boost Graph Library,修复节点大小
- 如何找到大小'x'数组是否完全填充,在C++?
- QTableView:endMoveRows在模型中重置水平页眉大小
- 大小相等但成员数量不同的结构之间的性能差异
- 如何在不知道向量大小的情况下输入向量内部的向量?
- 在c++中获取大文件的大小
- 为什么我不能将 rand() 与数组的大小一起使用?
- 类型总是使用其大小存储在内存中吗
- 在调用接收数组的方法时,模板化数组大小是不是一种糟糕的做法
- 在C++中传递给函数时,为什么要指定数组大小作为参数
- 为什么C++逐位AND运算符在不同大小的操作数中表现为这样
- 使用.find函数在c++中查找字符和另一个字符之间的大小