How allocate or free only parts of an array?

后端 未结 2 1324
悲哀的现实
悲哀的现实 2020-12-10 09:02

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 n

相关标签:
2条回答
  • 2020-12-10 09:26

    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.

    0 讨论(0)
  • 2020-12-10 09:37

    You can't free part of an array - you can only free() a pointer that you got from malloc() and when you do that, you'll free all of the allocation you asked for.

    As far as negative or non-zero-based indices, you can do whatever you want with the pointer when you get it back from malloc(). For example:

    int *array = malloc(10 * sizeof(int));
    array -= 2;
    

    Makes an array that has valid indices 2-11. For negative indices:

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

    Now you can access this array like array[-1], array[-4], etc.

    Be sure not to access memory outside your array. This sort of funny business is usually frowned upon in C programs and by C programmers.

    0 讨论(0)
提交回复
热议问题