Class 9 | Structure and Union | C Programming Notes

Structure and Union in C Programming

Structure

A structure is a user-defined data type in C that can store multiple values of the same or different data types under a single name.

The individual data items stored inside a structure are called members or elements of the structure.

For example, information about a student may contain:

  • Student ID
  • Name
  • Phone Number
  • Address
  • Marks

These values may have different data types, but they can all be grouped together using a structure.


Declaration of Structure and Structure Variables

A structure is declared using the struct keyword.

The struct statement defines a new user-defined data type containing one or more members.

Syntax

struct structure_name
{
    data_type member1;
    data_type member2;
    data_type member3;
};

Example

struct Employee
{
    int emp_id;
    char name[20];
    char address[20];
    float salary;
};

Here:

  • Employee is the structure name.
  • emp_id, name, address, and salary are structure members.

Declaring Structure Variables

Structure variables can be declared after defining the structure.

Example

struct Employee
{
    int emp_id;
    char name[20];
    char address[20];
    float salary;
};

struct Employee em1, em2, em3;

Here:

em1
em2
em3

are structure variables.


Declaring Variables With the Structure Definition

Structure variables can also be declared at the same time as the structure definition.

struct Employee
{
    int emp_id;
    char name[20];
    char address[20];
    float salary;
} em1, em2, em3;

Accessing Members of a Structure

The members of a structure are accessed using the dot operator (.).

Syntax

structure_variable.member_name

Examples

student.roll
student.name
student.address

Example: Accessing Structure Members

#include <stdio.h>

struct Student
{
    int roll;
    char name[20];
    char address[30];
};

int main(void)
{
    struct Student st;

    printf("Enter name: ");
    scanf("%19s", st.name);

    printf("Enter roll number: ");
    scanf("%d", &st.roll);

    printf("Enter address: ");
    scanf("%29s", st.address);

    printf("\nStudent Information\n");
    printf("Name: %s\n", st.name);
    printf("Roll No: %d\n", st.roll);
    printf("Address: %s\n", st.address);

    return 0;
}

Example Output

Enter name: Ram
Enter roll number: 12
Enter address: Attariya

Student Information
Name: Ram
Roll No: 12
Address: Attariya

Nested Structure

A nested structure is a structure that contains another structure as one of its members.

In other words, one structure is placed inside another structure.

Nested structures are useful when a complex record contains another group of related information.


Syntax

First, define one structure:

struct Structure1
{
    data_type member1;
    data_type member2;
};

Then use it as a member of another structure:

struct Structure2
{
    data_type member1;

    struct Structure1 variable1;
};

Example of Nested Structure

Suppose an employee has:

  • Employee ID
  • Name
  • Address information

The address itself may contain:

  • City
  • Street
  • Phone Number

We can define it using nested structures.

struct Address
{
    char city[20];
    char street[30];
    char phone[15];
};

struct Employee
{
    int emp_id;
    char name[20];

    struct Address add;
};

Accessing Members of a Nested Structure

Nested structure members are accessed using multiple dot operators.

Examples

emp.add.city
emp.add.street
emp.add.phone

Normal members of the outer structure can be accessed as:

emp.emp_id
emp.name

Example Program of Nested Structure

#include <stdio.h>

struct FirstName
{
    char first[20];
};

struct LastName
{
    char last[20];
};

struct FullName
{
    struct FirstName first_name;
    struct LastName last_name;
};

int main(void)
{
    struct FullName name;

    printf("Enter your first name: ");
    scanf("%19s", name.first_name.first);

    printf("Enter your last name: ");
    scanf("%19s", name.last_name.last);

    printf(
        "Your full name is: %s %s\n",
        name.first_name.first,
        name.last_name.last
    );

    return 0;
}

Example Output

Enter your first name: Ram
Enter your last name: Sharma
Your full name is: Ram Sharma

Array of Structures

An array of structures is a collection of structure variables of the same type stored under a single array name.

Just like arrays of integers or characters, we can create an array whose elements are structures.

For example:

struct Student st[5];

This creates five structure variables:

st[0]
st[1]
st[2]
st[3]
st[4]

Each element can store all the members of the Student structure.


Accessing Members of an Array of Structures

The members can be accessed using an array index followed by the dot operator.

Examples

st[0].roll
st[0].name
st[0].address

Another record can be accessed as:

st[1].roll
st[1].name
st[1].address

Example of Array of Structures

#include <stdio.h>

#define MAX_PEOPLE 5
#define MAX_NAME_LENGTH 30

struct Person
{
    char name[MAX_NAME_LENGTH];
};

int main(void)
{
    struct Person people[MAX_PEOPLE];
    int num_people;
    int i;

    printf("Enter the number of people: ");
    scanf("%d", &num_people);

    if (num_people > MAX_PEOPLE)
    {
        num_people = MAX_PEOPLE;
    }

    for (i = 0; i < num_people; i++)
    {
        printf("Enter name for person %d: ", i + 1);
        scanf("%29s", people[i].name);
    }

    printf("\nNames entered:\n");

    for (i = 0; i < num_people; i++)
    {
        printf("Person %d: %s\n", i + 1, people[i].name);
    }

    return 0;
}

Example Output

Enter the number of people: 3
Enter name for person 1: Ram
Enter name for person 2: Sita
Enter name for person 3: Hari

Names entered:
Person 1: Ram
Person 2: Sita
Person 3: Hari

Union

A union is also a user-defined data type in C.

Like a structure, a union can contain multiple members of the same or different data types.

However, the major difference is that all members of a union share the same memory location.

Therefore, only one member’s stored value is meaningful at a time.


Declaration of Union and Union Variables

A union is declared using the union keyword.

Syntax

union union_name
{
    data_type member1;
    data_type member2;
    data_type member3;
};

Example

union Data
{
    int id;
    float marks;
    char grade;
};

Here:

  • Data is the union name.
  • id, marks, and grade are union members.

Declaring Union Variables

A union variable can be declared as:

union Data data;

Multiple variables can also be declared:

union Data d1, d2, d3;

Here:

d1
d2
d3

are union variables.


Declaring Variables With Union Definition

Union variables can also be created at the same time as the union definition.

union Data
{
    int id;
    float marks;
    char grade;
} d1, d2;

Example of Union

#include <stdio.h>

union Data
{
    char name[50];
    int id;
};

int main(void)
{
    union Data data;

    printf("Enter a name: ");
    scanf("%49s", data.name);

    printf("Name: %s\n", data.name);

    return 0;
}

Accessing Members of a Union

Union members are accessed using the dot operator (.) in the same way as structure members.

Syntax

union_variable.member_name

Examples

data.id
data.name

Example of Accessing Union Members

#include <stdio.h>

union StudentData
{
    int roll;
    float marks;
};

int main(void)
{
    union StudentData student;

    student.roll = 10;

    printf("Roll Number: %d\n", student.roll);

    student.marks = 85.5f;

    printf("Marks: %.2f\n", student.marks);

    return 0;
}

Output

Roll Number: 10
Marks: 85.50

Important Point About Union

Consider:

union StudentData
{
    int roll;
    float marks;
};

When:

student.roll = 10;

the shared memory stores the roll number.

If we later write:

student.marks = 85.5;

the same memory location is reused for marks.

Therefore, we should not expect both values to remain stored independently at the same time.


Structure vs Union

Both structures and unions are user-defined data types, but their memory management is different.

StructureUnion
Defined using the struct keyword.Defined using the union keyword.
Each member has its own storage within the structure object.All members share the same storage.
All members can store valid values at the same time.Normally only the most recently stored member value should be treated as active.
Generally requires more memory than a union containing the same members.Generally requires less memory because members share storage.
Its size is large enough to store all members, including any padding added for alignment.Its size is large enough to store its largest member, including any alignment requirement.
Changing one member normally does not overwrite another member.Storing a value in one member reuses the same memory as other members.
Best when all members are required together.Best when only one of several possible values is required at a time.

Syntax of Structure and Union

Structure

struct structure_name
{
    data_type member1;
    data_type member2;
    data_type member3;
};

Union

union union_name
{
    data_type member1;
    data_type member2;
    data_type member3;
};

Example Comparing Structure and Union

#include <stdio.h>

struct StudentStructure
{
    int roll;
    float marks;
};

union StudentUnion
{
    int roll;
    float marks;
};

int main(void)
{
    struct StudentStructure s;
    union StudentUnion u;

    s.roll = 10;
    s.marks = 85.5f;

    printf("Structure:\n");
    printf("Roll = %d\n", s.roll);
    printf("Marks = %.2f\n", s.marks);

    u.roll = 10;

    printf("\nUnion after storing roll:\n");
    printf("Roll = %d\n", u.roll);

    u.marks = 85.5f;

    printf("\nUnion after storing marks:\n");
    printf("Marks = %.2f\n", u.marks);

    return 0;
}

Difference Between Structure and Union – Short Answer

BasisStructureUnion
Keywordstructunion
MemorySeparate storage for membersShared storage for members
ValuesAll members can retain values simultaneouslyOne active stored representation at a time
SizeUsually largerUsually smaller
Member AccessDot operator .Dot operator .
Best UseRelated data required togetherAlternative values sharing memory

Quick Revision

Structure

A structure is a user-defined data type that combines related variables of the same or different data types.

Example

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

Accessing Structure Members

Use the dot operator:

student.roll
student.name
student.marks

Nested Structure

A structure inside another structure is called a nested structure.

Example:

emp.add.city

Array of Structures

An array containing structure variables is called an array of structures.

struct Student st[5];

Access:

st[0].roll
st[0].name

Union

A union is a user-defined data type in which all members share the same memory location.

Example

union Data
{
    int id;
    float marks;
};

Accessing Union Members

data.id
data.marks

Important Exam Points

  • A structure is a user-defined data type.
  • The struct keyword is used to define a structure.
  • A structure can contain members of different data types.
  • Structure members are accessed using the dot (.) operator.
  • A structure inside another structure is called a nested structure.
  • An array of structures stores multiple structure records.
  • A union is defined using the union keyword.
  • Structure members have separate storage within the structure object.
  • Union members share the same storage.
  • A structure can keep values for all its members simultaneously.
  • In a union, writing to one member reuses the memory shared by the others.
  • Structures usually require more memory than unions with the same members.
  • Both structure and union members are accessed using the dot (.) operator.

Discussion

Share a helpful question, idea, or explanation with other students.

Leave a Comment

Write a clear question, answer, or helpful explanation.
Your email will not be published.

Download Our Offline App

Study class-wise notes even when internet is not available. Get the app from Play Store.

Nepal eNotes offline app preview
Get it on Google Play