rebbailey rebbailey - 2 months ago 5
C Question

How to delete elements of an array after a specified index

I am trying to remove the elements of an array that have an index greater than, or equal to a specified index value.

int values[] = {1,2,3,4,5,6,7};
int size_of_array = 7;
int specified_index = 3;

for(int i = size_of_array; i >= specified_index; size_of_array--){
values[middle_index + 1] = NULL;
}


I am very new to C so it is still a little confusing. Apologies if this is duplicate.

Answer

You cannot resize an array in C. Once it is created its size is fixed. If you are OK to use dynamic memory and a pointer instead of an array you could resize it using realloc.

However looking at your purposes you don't actually need to resize the array, you can just decrease size_of_array and ignore the remaining values, eg:

size_of_array -= 4;

Edit: To clarify what I mean by ignoring values. I assume that by creating an array you intend to actually so some work with its elements, else having the array would be pointless. Therefore when you do your work on the array, just only do it on elements which you are not ignoring. Let us for the sake of example say we want to print the values of the array as our "work":

void printArray(int *array, size_t size) {
    for (size_t itr = 0; itr < size; ++itr) { printf("%d", array[itr])); }
}

int main(int argc, char *argv[]) {
    int values[] = {1,2,3,4,5,6,7};
    int size_of_array = 7;
    int specified_index = 3;
    // Print the whole array
    printArray(values, size_of_array);
    // Print the 'shortened' array by ignoring the rest of the values
    size_of_array -= 4;
    printArray(values, size_of_array);
}
Comments