Search code examples
cmallocdynamic-memory-allocationrealloc

Using realloc() to remove data from the beginning of an allocated segment?


Say I have a dynamically allocated array:

int * arr = (int *) malloc(sizeof(int) * oldSize);
for(int i = 0; i < oldSize; i++){
    arr[i] = i;
}

and I wanted to shrink that memory segment to a size newSize so that arr only consists of:

{oldSize - newSize, ... oldSize - 1}

Is it possible to do this without going through every single element in the array (aside from the first n elements, where n is oldSize - newSize) and shifting them back n positions before calling arr = realloc(arr, sizeof(int) * newSize)?


Solution

  • You'll need to move the elements you want to keep to the start of the list. Fortunately, there's a function for this, memmove:

    memmove(arr, arr + (oldsize-newsize), newsize * sizeof(int));