Vospala
Vospala

Reputation: 51

Shift allocated memory

I have this code:

int items = 2;
int *array = malloc(items * sizeof(int));
array[0] = 1;
array[1] = 2;

I want to pop first item and shift allocated memory just from the left side to do:

array[0] == 2

Probably need to get address of array and shift it for poped_items * sizeof(int) or something like this? What should be the first realloc argument?

Upvotes: 0

Views: 662

Answers (1)

Petr Skocik
Petr Skocik

Reputation: 60067

If you need to remove items on the left (and simply working with &array[ItemsToShift] instead of a plain array isn't enough), don't realloc, just memmove:

memmove(&array[0], &array[1], (items-(&array[1]-array[0]))*sizeof(int));

If you want, you can make it a type generic macro:

#define DARRAY_shift(Array, Size, Nshift) \
    memmove(&array[0], \
            &array[Nshift], \
            (Size-(&array[Nshift]-&array[0]))*sizeof(Array[0]) \
           );

You could realloc after the memmove:

new_array = realloc(array, (Size-Nshift)*sizeof(array[0]));

but that's potentially a waste of cycles as you can just ignore the gap at the end of your dynamic array created by the shift.

Upvotes: 1

Related Questions