你怎么在C ++中的`realloc`? [英] How do you `realloc` in C++?

查看:189
本文介绍了你怎么在C ++中的`realloc`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在C ++中 realloc ?它似乎缺少从语言 - 有删除但不是 resize

How can I realloc in C++? It seems to be missing from the language - there is new and delete but not resize!

我需要它,因为我的程序读取更多的数据,我需要重新分配缓冲区来保存它。我不认为删除旧的指针和新的,更大的,是正确的选择。

I need it because as my program reads more data, I need to reallocate the buffer to hold it. I don't think deleteing the old pointer and newing 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)

p>

use

Foo(&t[0])

这是绝对正确的C ++代码,因为vector是一个聪明的C数组。

It is absolutely correct C++ code, because vector is a smart C-array.

这篇关于你怎么在C ++中的`realloc`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆