Suppose, I have an array as follows:
arr[5]={1 2 3 4 3};
Now I want to search 3 and delete it. But in this array there two 3 are available. So, I want to delete both 3. How to do that?
Suppose, I have an array as follows:
arr[5]={1 2 3 4 3};
Now I want to search 3 and delete it. But in this array there two 3 are available. So, I want to delete both 3. How to do that?
Since you have a statically allocated array, it has a fixed size, and elements can't be deleted from it. So I'm going to assume you are talking figuratively, wanting a new array without those elements.
Approach one:
First, we need to find the size of the new array so we can allocate an array of the correct size.
size_t old_size = sizeof(arr)/sizeof(arr[0]);
size_t new_size = old_size;
for (size_t i=0; i<old_size; ++i) {
if (arr[i] == to_remove) {
--new_size;
}
}
If new_size
is zero, we should just set new_array
to NULL
and skip the rest.
Otherwise, we're now ready to allocate the new array.
int *new_array = malloc(sizeof(int) * new_size);
if (!new_array) {
perror("malloc");
exit(EXIT_FAILURE);
}
Finally, we can copy the selected elements.
for (size_t i=0, j=0; i<old_size; ++i) {
if (arr[i] != to_remove) {
new_array[j++] = arr[i];
}
}
Alternatively, we can start by over-allocating.
int *new_array = malloc(sizeof(int) * new_size);
if (!new_array) {
perror("malloc");
exit(EXIT_FAILURE);
}
Then copy the selected elements.
size_t old_size = sizeof(arr)/sizeof(arr[0]);
for (size_t i=0, new_size=0; i<old_size; ++i) {
if (arr[i] != to_remove) {
new_array[new_size++] = arr[i];
}
}
Then shrink the array size to what's required.
if (new_size) {
int *temp = realloc(new_array, sizeof(int) * new_size);
if (temp) {
new_array = temp;
}
} else {
free(new_array);
new_array = NULL;
}
@ikegami provides a solution returning a new allocated array, you can also work in place (memmove
elements to the left) keeping count of how many elements the array has after deletion:
#include <stdio.h>
#include <string.h>
static size_t del(int *arr, size_t size, int elem)
{
for (size_t i = 0; i < size;)
{
if (arr[i] == elem)
{
if (i < --size)
{
memmove(&arr[i], &arr[i + 1], (size - i) * sizeof(*arr));
}
}
else
{
i++;
}
}
return size;
}
int main(void)
{
int arr[] = {1, 2, 3, 4, 3}; // do not hardcode the nr of elements
size_t size = sizeof arr / sizeof *arr;
for (size_t i = 0; i < size; i++)
{
printf("arr[%zu] = %d ", i, arr[i]);
}
printf("\nAfter deletion:\n");
size = del(arr, size, 3);
for (size_t i = 0; i < size; i++)
{
printf("arr[%zu] = %d ", i, arr[i]);
}
printf("\n");
return 0;
}
Output:
arr[0] = 1 arr[1] = 2 arr[2] = 3 arr[3] = 4 arr[4] = 3
After deletion:
arr[0] = 1 arr[1] = 2 arr[2] = 4