Reputation: 39
I am new to c and was wondering if there are any built in operations to remove a specified element from an array.
for example if I wanted to remove the even elements in an array
for(.....) //goes through the array one by one
if(nums[i] / 2 = 0)
nums[i].remove;
What could I put instead of .remove to remove the number.
on a separate note if anybody knows a good documentation website for other c array operations would you be able to link it?
Upvotes: 1
Views: 78
Reputation: 4862
You would need to loop through your array starting at the item you want to remove and then copy each successive array item into the one before it. e.g. Shift the array items to the left.
Once you have done that, you can use realloc()
to trim the last array item off of the allocated memory. You'll of course need to do the math to determine the size of each array item and pass realloc()
the original size of the array minus the one that you are going to "trim off".
Other options would bememmove
and memcopy
, but then you get into all kinds of extra temp buffers.
An example of "manually" shifting array items:
int* items = NULL;
int arraySize = 10;
int itemToRemove = 5;
items = (int*)malloc(sizeof(int) * arraySize);
//Initialize the array with some dummy values.
for (int i = 0; i < arraySize; i++)
{
items[i] = (i * 100);
}
//Print out the contents of the array - before we remove an item.
printf("Before removing item:\n");
for (int i = 0; i < arraySize; i++)
{
printf("items[%d]: %d\n", i, items[i]);
}
//Shift each array item left, starting at the item specified by "itemToRemove".
for (int i = itemToRemove; i < arraySize; i++)
{
items[i] = items[i + 1];
}
arraySize--; //Be sure to keep track of the new array size.
//Reallocate the array, this will trim the size of the allocated block of memory.
items = (int*)realloc(items, sizeof(int) * arraySize);
//Print out the contents of the array - after we remove an item.
//** NOTICE: The array now only contains 9 items and the 5th one contains the data previously held in the 6th, etc.
printf("After removing item:\n");
for (int i = 0; i < arraySize; i++)
{
printf("items[%d]: %d\n", i, items[i]);
}
//Be sure to cleanup when done. :)
free(items);
Upvotes: 0
Reputation: 58868
No, elements cannot be removed from an array.
An array has a certain size from the moment you create it and that size cannot be changed.
Upvotes: 4