Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

c - How allocate or free only parts of an array?

See this example:

int *array = malloc (10 * sizeof(int))

Is there a way to free only the first 3 blocks?

Or to have an array with negative indexes, or indexes that don't begin with 0?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't directly free the first 3 blocks. You can do something similar by reallocating the array smaller:

/* Shift array entries to the left 3 spaces. Note the use of memmove
 * and not memcpy since the areas overlap.
 */
memmove(array, array + 3, 7);

/* Reallocate memory. realloc will "probably" just shrink the previously
 * allocated memory block, but it's allowed to allocate a new block of
 * memory and free the old one if it so desires.
 */
int *new_array = realloc(array, 7 * sizeof(int));

if (new_array == NULL) {
    perror("realloc");
    exit(1);
}

/* Now array has only 7 items. */
array = new_array;

As to the second part of your question, you can increment array so it points into the middle of your memory block. You could then use negative indices:

array += 3;
int first_int = array[-3];

/* When finished remember to decrement and free. */
free(array - 3);

The same idea works in the opposite direction as well. You can subtract from array to make the starting index greater than 0. But be careful: as @David Thornley points out, this is technically invalid according to the ISO C standard and may not work on all platforms.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...