Nano Technology

Structures in C Programming


1. What is a Structure?

A structure in C is a user-defined data type that allows grouping of variables of different data types under a single name. Structures are used to represent complex data more logically.

For example, student details such as roll number, name, and marks can be grouped together using a structure.

Structures in C Programming

2. Structure Declaration

Structure declaration defines a new data type using the struct keyword. It specifies the members (variables) of the structure.


struct student
{
    int roll;
    char name[20];
    float marks;
};

Here, student is a structure containing three different data members.

3. Accessing Structure Members

Structure members are accessed using the dot operator (.). A structure variable must be declared before accessing its members.


struct student s1;
s1.roll = 101;
s1.marks = 85.5;

Each member of the structure can be accessed and modified individually.

4. Array of Structures

An array of structures is used to store information about multiple objects of the same type.


struct student s[3];

Each element of the array represents a structure variable and can store complete information of one student.

5. Structure vs Union

Structure Union
Allocates memory for all members Shares memory among members
All members can be accessed at a time Only one member is used at a time
Requires more memory Memory efficient
Used when all data members are needed Used when only one member is needed

6. Nested Structures

A nested structure is a structure that contains another structure as its member. This allows representation of complex data relationships.


struct date
{
    int day, month, year;
};

struct student
{
    int roll;
    struct date dob;
};

Nested structures are useful in real-world applications where data has hierarchical relationships.

7. Examples


#include <stdio.h>

struct student
{
    int roll;
    float marks;
};

int main()
{
    struct student s1 = {101, 92.5};

    printf("Roll Number: %d\n", s1.roll);
    printf("Marks: %.2f\n", s1.marks);

    return 0;
}

This program demonstrates structure declaration, initialization, and member access.

8. Applications

  • Storing student and employee records
  • Representing complex data structures
  • File handling using structured data
  • Implementing databases and records
  • Real-world modeling of objects
Note: Understanding structures is essential before learning file handling, dynamic memory allocation, and data structures.