简体   繁体   中英

Can I realloc from a position of the array?

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?

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.

Just use array += 2 or array = &array[2] . You can't realloc() it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM