Reputation:
Say I declared an 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}
.
Dismiss the first 2 elements. So it would start on array[2]
. Reallocing 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 using &array[2], *array[2]
, nor creating an auxiliary array, reallocing Array to AuxArr than free(AuxArr).
Can I get a light?
Upvotes: 4
Views: 1177
Reputation: 480
Just use array += 2
or array = &array[2]
. You can't realloc()
it.
Upvotes: 0
Reputation: 111
You can only realloc a pointer to a memory block that has already been alloc'ed. So you can realloc(array), but not array[2] since that is a pointer to a location in the middle of a memory block.
You may want to try memmove instead.
Edit:In response to ThingyWotsit's comment, after memomving the data you want to the front of the array, then you can realloc to drop off the tail end.
Upvotes: 6