Reallocating memory of a C++ array. [duplicate]

六眼飞鱼酱① 提交于 2019-12-06 01:39:35

You can't - that's why in C++ you use std::vector<>.

If you wanted to do this, you'd have to allocate a new array (via new), then copy the old items across (std::copy for example), then delete[] the previous array.

Just use std::vector - let it do all that stuff for you...

In general C++ arrays cannot be reallocated with realloc, even if the storage was allocated with malloc. malloc doesn't give you arrays. It gives pointers to usable storage. There's a subtle difference here.

For POD types, there's little difference between usable storage and actual objects. But for non-POD types, usable storage and objects are totally different things.

realloc gives you a larger portion of usable storage. It manipulates storage not objects. That may work fine for POD types, but for other types it's a recipe for disaster.

Daniel Rose

Use ::std::vector.

Take a look at this question or this question for more details.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!