Open In App

How to Delete an Element from an Array of Structs in C?

Last Updated : 14 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




// C program to delete an element from an array of structure
  
#include <stdio.h>
#include <string.h>
  
struct Person {
    char name[50];
    int age;
};
  
#define MAX_PERSONS 10
  
// function to print the content of array of structure
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()
{
  
    // intializing array of structure
    struct Person persons[MAX_PERSONS] = {
        { "Person1", 25 },
        { "Person2", 30 },
        { "Person3", 22 },
  
    };
  
    int MAX_PERSONS_CURRENT
        = 3; // Initial size of the array
  
    // Identifying the Element to Delete
    const char* nameToDelete = "Person2";
    int indexToDelete = -1;
  
    // Finding the index of the person to delete
    for (int i = 0; i < MAX_PERSONS_CURRENT; ++i) {
        if (strcmp(persons[i].name, nameToDelete) == 0) {
            indexToDelete = i;
            break;
        }
    }
  
    // Checking if the person was found
    if (indexToDelete == -1) {
        printf("Person with name %s not found.\n",
               nameToDelete);
    }
    else {
        // Deleting the Element
        for (int i = indexToDelete;
             i < MAX_PERSONS_CURRENT - 1; ++i) {
            persons[i] = persons[i + 1];
        }
  
        // Adjusting the Array Size
        MAX_PERSONS_CURRENT--;
  
        // Displaying the Updated Array
        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)

 

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads