How to Delete an Element from an Array of Structs in C?
Last Updated :
14 Feb, 2024
In C, an array of structs refers to the array that stores the structure variables as its elements. In this article, we will learn how to delete an element from an array of structures in C.
For Example,
Input:
struct Person persons[3] = {
{ "Person1", 25 },
{ "Person2", 30 },
{ "Person3", 22 },
};
TargetToDelete= "Person2"
Output:
Array of Persons after deletion:
Name: Person1, Age: 25
Name: Person3, Age: 22
Remove an Element from an Array of Structure in C
We cannot directly remove the element for an array in C so to remove an element from an array of structures, we need to overwrite the target element that we want to remove by shifting all elements after the target element one position toward the beginning of the array.
C Program to Delete an Element from an Array of Structure
The below example demonstrates how we can remove the element from an array of structures in C.
C
#include <stdio.h>
#include <string.h>
struct Person {
char name[50];
int age;
};
#define MAX_PERSONS 10
void displayPersons( struct Person persons[], int count)
{
printf ( "Array of Persons after deletion:\n" );
for ( int i = 0; i < count; ++i) {
printf ( "Name: %s, Age: %d\n" , persons[i].name,
persons[i].age);
}
printf ( "\n" );
}
int main()
{
struct Person persons[MAX_PERSONS] = {
{ "Person1" , 25 },
{ "Person2" , 30 },
{ "Person3" , 22 },
};
int MAX_PERSONS_CURRENT
= 3;
const char * nameToDelete = "Person2" ;
int indexToDelete = -1;
for ( int i = 0; i < MAX_PERSONS_CURRENT; ++i) {
if ( strcmp (persons[i].name, nameToDelete) == 0) {
indexToDelete = i;
break ;
}
}
if (indexToDelete == -1) {
printf ( "Person with name %s not found.\n" ,
nameToDelete);
}
else {
for ( int i = indexToDelete;
i < MAX_PERSONS_CURRENT - 1; ++i) {
persons[i] = persons[i + 1];
}
MAX_PERSONS_CURRENT--;
displayPersons(persons, MAX_PERSONS_CURRENT);
}
return 0;
}
|
Output
Array of Persons after deletion:
Name: Person1, Age: 25
Name: Person3, Age: 22
Time Complexity: O(N), where N is the size of the array.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...