Structures (Lesson)

Structures: User-Defined Data Types

A structure is a collection of variables of different types under a single name. While arrays store many items of the same type, structs allow you to combine integers, floats, and strings.

16.1 Defining a Structure

Use the struct keyword followed by the structure template.

struct Student {
    int id;
    char name[50];
    float marks;
};

16.2 Declaring and Accessing Members

Use the dot operator (.) to access individual members.

struct Student s1;
s1.id = 101;
s1.marks = 85.5;

16.3 Nested Structures

You can place a structure inside another structure.

struct Address {
    int cityId;
    char city[20];
};

struct Person {
    char name[20];
    struct Address addr; // Nested
};

16.4 Arrays of Structures

Useful for storing records of many entities of the same type (like a class of students).

struct Student class[50];
class[0].id = 1;
class[1].id = 2;

16.5 Structure size

The size of a structure is the sum of its members, often with some extra "padding" bytes added by the compiler for memory alignment.

sizeof(struct Student);

Example: Employee Record System

#include <stdio.h>

struct Employee {
    char name[30];
    int id;
    float salary;
};

int main() {
    struct Employee emp;

    printf("Enter name: ");
    scanf("%s", emp.name);
    printf("Enter ID: ");
    scanf("%d", &emp.id);
    printf("Enter Salary: ");
    scanf("%f", &emp.salary);

    printf("\n--- Employee Info ---\n");
    printf("Name: %s\n", emp.name);
    printf("ID: %d\n", emp.id);
    printf("Salary: %.2f\n", emp.salary);

    return 0;
}

Refer to the Lecture Slides for a comparison between Structures and Unions.

PREVIOUS
Strings
NEXT
File Handling