Answer the question
In order to leave comments, you need to log in
How to remove 5 from an array?
How to discard 5 from an array in C?
Answer the question
In order to leave comments, you need to log in
the most transparent way in my opinion (C has already been forgotten, and the compiler was only pluses at hand: some syntactic roughness is possible)
#include "stdio.h"
void shiftArray(int* array, int* length, int startIndex=5){
int index;
if(startIndex < *length){
for(index=startIndex + 1; index < *length; index++){
array[index-1] = array[index];
}
*length -= 1;
}
}
int main()
{
int len1 = 10;
int len2 = 3;
int arr1[len1];
int arr2[len2];
for(int i=0;i<len1;i++)
arr1[i] = i;
for(int i=0;i<len2;i++)
arr2[i] = i;
shiftArray(arr1, &len1);
shiftArray(arr1, &len2);
for(int i=0;i<len1;i++)
printf("%d ", arr1[i]);
printf("\n");
for(int i=0;i<len2;i++)
printf("%d ", arr2[i]);
printf("\n");
return 0;
}
You can't just take and remove an element from an array in C.
In principle, nothing can be removed from a static array - its size never changes.
In dynamic arrays, there are options:
You can rewrite the tail of the array, starting from the sixth element, one element forward, i.e. 6 element will become 5, and so on. But at the same time, an unused element is formed at the end, you can get rid of it by re-allocating the array using realloc, for example. But if you do this, then it's easier to immediately allocate memory for a new array and copy the entire first array, except for the element to be deleted, as GavriKos wrote .
Another option is to mark similar unused elements in some way. Either write some value in them, indicating for you that this is an unused element, or store somewhere separately the used size of the array (as is done in std::vector).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question