您如何在C ++中“重新分配"? [英] How do you 'realloc' in C++?
本文介绍了您如何在C ++中“重新分配"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在C ++中realloc
?该语言似乎缺少了-有new
和delete
,但没有resize
!
How can I realloc
in C++? It seems to be missing from the language - there is new
and delete
but not resize
!
我需要它,因为随着程序读取更多数据,我需要重新分配缓冲区以容纳它.我认为delete
选择旧指针并new
选择新的更大指针不是正确的选择.
I need it because as my program reads more data, I need to reallocate the buffer to hold it. I don't think delete
ing the old pointer and new
ing a new, bigger one, is the right option.
推荐答案
使用:: std :: vector!
Use ::std::vector!
Type* t = (Type*)malloc(sizeof(Type)*n)
memset(t, 0, sizeof(Type)*m)
成为
::std::vector<Type> t(n, 0);
然后
t = (Type*)realloc(t, sizeof(Type) * n2);
成为
t.resize(n2);
如果要将指针传递给函数,而不是
If you want to pass pointer into function, instead of
Foo(t)
使用
Foo(&t[0])
这是绝对正确的C ++代码,因为向量是一个智能C数组.
It is absolutely correct C++ code, because vector is a smart C-array.
这篇关于您如何在C ++中“重新分配"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文