Skip to content

Defining and processing a structure

Let’s walk through the process of defining and processing a structure in C with an example. We’ll create a simple program that defines a structure to represent information about employees, and then we’ll demonstrate how to create, manipulate, and display data using this structure.

#include <stdio.h>

#include <string.h>

// Define a structure to represent an employee

struct Employee {

    char name[50];

    int employeeID;

    float salary;

};

int main() {

    // Declare variables of type ‘struct Employee’

    struct Employee emp1, emp2;

    // Initialize data for emp1

    strcpy(emp1.name, “John Doe”);

    emp1.employeeID = 1001;

    emp1.salary = 50000.0;

    // Initialize data for emp2

    strcpy(emp2.name, “Jane Smith”);

    emp2.employeeID = 1002;

    emp2.salary = 60000.0;

    // Display employee information

    printf(“Employee 1\n”);

    printf(“Name: %s\n”, emp1.name);

    printf(“Employee ID: %d\n”, emp1.employeeID);

    printf(“Salary: $%.2f\n\n”, emp1.salary);

    printf(“Employee 2\n”);

    printf(“Name: %s\n”, emp2.name);

    printf(“Employee ID: %d\n”, emp2.employeeID);

    printf(“Salary: $%.2f\n\n”, emp2.salary);

    // Update salary for emp2

    emp2.salary = 65000.0;

    // Display updated employee information

    printf(“Updated Salary for Employee 2\n”);

    printf(“Name: %s\n”, emp2.name);

    printf(“Employee ID: %d\n”, emp2.employeeID);

    printf(“Updated Salary: $%.2f\n”, emp2.salary);

    return 0;

}

In this example:

  • We define a structure Employee with three members: name, employeeID, and salary.
  • We declare two variables emp1 and emp2 of type struct Employee.
  • We initialize data for emp1 and emp2 using the strcpy function to copy the name string and simple assignments for the other members.
  • We display the information for both employees using printf.
  • We update the salary for emp2.
  • Finally, we display the updated information for emp2.

This program demonstrates the basic process of defining a structure, declaring structure variables, initializing and accessing structure members, and modifying structure data. Structures provide a convenient way to organize and manipulate related data elements in C programs.