Suppose I have a character array allocated with new.Now, if I want to modify the size of the array then which of the following two is the best method ? 1. using realloc function OR 2.Allocate a new array, copy the data from old array to the new array and then delete the old array.
问问题
1738 次
4 回答
2
使用 malloc(不是新的)分配块,然后使用 realloc。realloc 知道在扩展块之后有多少可用空间。
s2 = realloc(s,<size>);
if (s2) {
s = s2;
}
else {
free up s and handle the error
}
我见过的大多数代码都不能正确处理 realloc 的失败。
于 2013-01-04T20:32:34.047 回答
1
您不能将 realloc 可移植地应用于使用 new 分配的缓冲区。因此,只有您的第二种选择是可行的。
考虑切换到 std::vector 和 std::string。
于 2013-01-04T20:33:14.153 回答
1
我认为您是从 C 的角度考虑整个问题。
如果您正在处理数组使用 a vector
,它是动态的并且避免了您在问题中陈述的问题
例如
vector v(10); // allocates an array of 10 initialized to 0
v.push_back(42); // added another, so now array is 11 long
于 2013-01-04T20:38:16.953 回答
1
如果realloc
发现块后没有足够的可用空间,第一个选项也意味着复制。(即使您用于malloc
分配数组,这也是唯一正确的选择realloc
。)
但是,如果在每次重新分配时将数组的大小加倍(或将其大小乘以 > 1 的常数),则“将数组加一”操作平均使用常数时间。搜索恒定摊销时间。
假设一个初始大小为 n 的数组。重新分配到新的大小 2n 和复制成本 2n 步骤,但下一个 n“增加”操作是免费的。
顺便说一句,这就是std::vector
内部实现的方式以及许多其他数组容器。
于 2013-01-04T20:38:57.090 回答