0

I have a array in c++ like this

int* arr = new int[8];

How can I add add 4 more to the limit of arr push the limit to 12.

  • You cannot do that. Allocate new array and copy existing elements. – MikeCAT May 18 '21 at 17:11
  • 2
    A `std::vector` is the traditional datatype used to manage what you describe. – Drew Dormann May 18 '21 at 17:13
  • @MikeCAT strictly speaking, this is incorrect. For array of integers, OP can use `malloc` to allocate initial array, and than use `realloc` in attempt to increase allocated area. – SergeyA May 18 '21 at 17:23
  • @SergeyA What MikeCAT said is correct for C++'s `new[]`. And you can't mix C's `malloc()`/`realloc()` with C++'s `delete[]`, either. You would have to use C's `free()` instead. In any case, `realloc()` will do a new allocate+copy if it can't expand the array in-place. – Remy Lebeau May 18 '21 at 17:26
  • @SergeyA Be careful when using `malloc()` in C++. It may not work with complicated classes like `std::string` because it doesn't do required initialization by default. – MikeCAT May 18 '21 at 17:27
  • @MikeCAT "*[malloc] doesn't do required initialization by default*" - more accurately, replace "by default" with "at all". – Remy Lebeau May 18 '21 at 17:28
  • @RemyLebeau I am well aware of non-mixable allocations. But I said so explicitly: `use malloc to allocate initial array,`. – SergeyA May 18 '21 at 17:45
  • @MikeCAT I am well aware of this as well. This is why I highlighted the fact that OP is using array if `int`s. – SergeyA May 18 '21 at 17:45

0 Answers0