Can I re-infer from an array position?

Let's say I announced array[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

. Later I want it to be array[8] = {2, 3, 4, 5, 6, 7, 8, 9}

.

Reset the first 2 items. So it will start with array[2]

. Redistribution array

to array[2]

.

I tried:

int *array=(int*)malloc(10*sizeof(int));
...//do stuffs
array=(int*)realloc(array[2],8*sizeof(int));

      

It didn't work. Neither with the help &array[2], *array[2]

, nor with the creation of an auxiliary array, reallocating the array in AuxArr than free (AuxArr).

Can you get light?

+3


source to share


2 answers


You can redirect a pointer to a block of memory that has already been assigned. Thus, you can realloc (array), but not array [2], since it is a pointer to a location in the middle of a block of memory.

You can try memmove instead .



Edit: In response to ThingyWotsit's comment, after you've written the data you want before the front of the array, you can reallocate it from the end.

+6


source


Just use array += 2

or array = &array[2]

. You cannot have realloc()

it.



0


source







All Articles