Suppose I set an array like this:

int *p,q; ///q мне предварительно известно p=new int q; 

So, how can I increase the number of elements in the array if necessary?

  • and can use std::vector<int> ? And if you need to be able to change and work with pointers, then realloc. - KoVadim
  • one
    @KoVadim, realloc is relevant only when allocated through malloc / calloc. - skegg
  • one
    and I did not claim that it will work with new. And with proper cooking, realloc can only memory and allocate them. - KoVadim
  • And delete too. - avp

2 answers 2

If you do not want to use the native C ++ STL vector<int> , then instead of new/delete you can use absolutely POSIX malc malloc/realloc/free from libc.

Actually, you can get by with one realloc(ptr, size) , skillfully controlling the values ​​of ptr and size .

See man 3 realloc .

    No Only by creating a new dynamic array and copying the old one there.

    In real projects in such cases, in order to allocate memory each time, allocate it with a margin.