Build a better website in less than an hour with GoDaddy
Ad Get started today for FREE! no tech skills required. Get found on Google and top sites like Facebook

Standard shrinkable arrays

Arrays created by the new[] operator should be shrinkable by the delete[] operator.

int main(){
 int*a=new int[100];
 //shrink array
 delete[90]a;
 //a contains only 10 ints
 delete[]a;
 return 0;
}

Example initialize undefined size arrays

Sometimes it is not possible to know the size of an array before allocating it.

If the programmer wants to avoid the waste of memory using non-shrinkable arrays, it would be required to create a new array with the correct size and delete the old array after copying its elements.

Note that it is also possible to use other implementations, such as linked lists or some others that allow dynamic size.

For cases where the arrays have a defined maximum size, its elements must be sequentially aligned and its real size is unknown before the allocation, it would be useful to have shrinkable arrays.

#include<cstdlib>

int main(){
 int a=rand()%1024+1,b=0;
 int*c=new int[a];
 for(unsigned i=0;i<a;++i)
  if(rand()%2)c[b++]=i;
 delete[a-b];
}

Example free data as soon it becomes useless

In some cases, when a program ends to compute some data, it becomes useless and to free it, could allow other applications to use its memory blocks.

For NP-complete optimization problems one may require more memory for finding non-optimal solutions and a lot of time for finding the optimal solution.

With shrinkable arrays the ability of freeing the unused allocated memory could enable its usage for other purposes.

int main(){
 data*a=new data[1024];
 for(unsigned b=1023;b>=0;--b){
  //computation time 1 month
  compute(a[b]);
  delete[1]a;
 }
 return 0;
}