Dynamically increase/decrease array size

前端 未结 4 602
难免孤独
难免孤独 2021-01-05 18:49

I\'m trying to increase the size of an array dynamically. Is there any standard C or C++ function, which appends additional space at the end of an array or removes it? I kno

相关标签:
4条回答
  • 2021-01-05 19:22

    After much experimentation by folks like professors and engineers (that have real jobs over some number of years,) when expanding an array, expand it by 50% unless you have inside information that tells you different. realloc() does all the heavy lifting for you too (explained next.) From the Internet:--> The realloc() function changes the size of the memory block pointed to by ptr to size bytes. The contents will be unchanged in the range from the start of the region up to the minimum of the old and new sizes. If the new size is larger than the old size, the added memory will not be initialized. If ptr is NULL, then the call is equivalent to malloc(size), for all values of size; if size is equal to zero, and ptr is not NULL, then the call is equivalent to free(ptr). Unless ptr is NULL, it must have been returned by an earlier call to malloc(), calloc() or realloc(). If the area pointed to was moved, a free(ptr) is done.

    0 讨论(0)
  • 2021-01-05 19:36

    There is no C functions as such. you can go for C++ container. This has Arrays, lists etc...

    0 讨论(0)
  • 2021-01-05 19:45

    probably you can achieve this by writing your own memory management wrapper such a way to append/release memory chunks from allocated array.

    0 讨论(0)
  • 2021-01-05 19:48

    The function you're looking for is realloc() in C, which is also present in the C++ STL as std::realloc

    Though as you mentioned C++, you could also go for an standard container like std::vector which encapsulate the associated memory management.

    0 讨论(0)
提交回复
热议问题