Unit 4: Structure




Introduction to Structures

A structure is a collection of variables of different data types grouped together under one name.

Defined using the keyword struct.

Defining and Declaring a Structure

A. Structure Definition

Syntax:

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

Example:

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

This only defines the structure — it does not create memory.

B. Declaring Structure Variables

Method 1: After structure definition

struct student s1, s2;

Method 2: Inside structure (recommended)

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

Initializing a Structure

A. Direct initialization

struct student s1 = {101, "Rahul", 85.5};

B. Assign each value separately

s1.roll = 101; strcpy(s1.name, "Rahul"); s1.marks = 85.5;

Accessing Structure Members

Use the dot operator (.) for accessing members.

Example:

printf("%d", s1.roll); printf("%s", s1.name); printf("%.2f", s1.marks);

Operations on Individual Members

You can perform all normal operations on structure members.

Example:

s1.marks += 10; // arithmetic s1.roll = s2.roll; // assignment strcpy(s1.name, "Raj"); // string operation

Members behave like normal variables.

Operations on Structures

Allowed:

✔ Assign one structure variable to another (same type)

s2 = s1;

✔ Passing structure to a function
✔ Returning a structure
✔ Structure pointers

Not Allowed:

❌ Direct comparison (==, !=)
❌ Arithmetic on entire structures

Structure Within Structure (Nested Structure)

A structure can contain another structure as a member.

Example:

struct address { int house_no; char city[20]; }; struct student { int roll; char name[20]; struct address addr; // nested structure };

Accessing:

s1.addr.house_no = 123; strcpy(s1.addr.city, "Delhi");

Array of Structures

Used when you want to store multiple data records, e.g., list of students.

Example:

struct student s[3];

Input:

for (int i = 0; i < 3; i++) { scanf("%d", &s[i].roll); scanf("%s", s[i].name); scanf("%f", &s[i].marks); }

Accessing:

printf("%d", s[1].roll);

Pointer to Structure

You can create pointers to structures and access members using arrow operator (->).

Example:

struct student *ptr; ptr = &s1; printf("%d", ptr->roll); printf("%s", ptr->name);

Arrow vs Dot

  • s1.roll → dot for normal variable
  • ptr->roll → arrow for pointer

    Passing Structures to Functions

    A. Pass by value

    void display(struct student s) { ... }

    B. Pass by pointer (preferred)

    void display(struct student *s) { printf("%d", s->roll); }

    Example: Full Program Using Structure

    #include <stdio.h> #include <string.h> struct student { int roll; char name[20]; float marks; }; int main() { struct student s1; s1.roll = 101; strcpy(s1.name, "Ankit"); s1.marks = 88.5; printf("Roll = %d\n", s1.roll); printf("Name = %s\n", s1.name); printf("Marks = %.2f\n", s1.marks); return 0; }

    Summary Table

    Concept Meaning
    Structure User-defined datatype
    Access operator Dot .
    Nested structure Structure inside structure
    Array of structure Multiple items of same struct
    Pointer to structure Uses ->
    Structure initialization Using { } or assignment
    Allowed operations Assignment, function call
    Not allowed Structure comparison & arithmetic

    Union in C

    A union in C is a special data type that allows you to store different data types in the same memory location.

    • It is similar to a structure.
    • BUT in structure each member has its own memory.
    • In union, all members share the same memory.

      This means only one member can store a value at a time.

      Declaring a Union

      Syntax:

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

      Example:

      union Data { int i; float f; char ch; };

      Usage of Unions

      You create a union variable just like a structure variable.

      Example:

      union Data d;

      Then assign values:

      d.i = 10; // stores integer d.f = 20.5; // now integer value is lost, float is stored d.ch = 'A'; // now float is lost, char is stored

      Because they share the same memory, storing something new replaces the previous.

      Operations on Union

      You can access the members using dot (.) operator:

      printf("%d", d.i); printf("%f", d.f); printf("%c", d.ch);

      ⚠ Only the last stored member will hold the correct value.

      Enumerated Data Types (enum)

      An enum (enumeration) allows you to create a list of named integer constants.

      • Makes the code easier to read and understand.
      • Default values start from 0, 1, 2, … automatically.

        Declaring Enum

        Syntax:

        enum enum_name { value1, value2, value3 };

        Example:

        enum Weekday { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };

        Here:

        • Monday = 0
        • Tuesday = 1
        • Wednesday = 2 ... and so on.

          Using enum Variable

          enum Weekday today; today = Wednesday;

          Assign Custom Values

          enum Level { Low = 1, Medium = 5, High = 10 };

          Difference Between Structure and Union (Quick Table)

          Feature Structure Union
          Memory Each member has separate memory All members share the same memory
          Size Sum of all members Size of the largest member
          Simultaneous storage Can store all values at once Only one member at a time
          Use Case Multiple data needed together Efficient memory usage

          Storage Classes in C 

          A storage class in C defines four things about a variable:

          1. Lifetime – how long the variable exists in memory
          2. Scope – where the variable can be accessed
          3. Default value
          4. Memory location

            C provides 4 storage classes:

            1. auto (Automatic)
            2. register
            3. static
            4. extern (External)

              Automatic Storage Class (auto)

              • Local variables inside a function are automatic by default.
              • You don’t need to write auto keyword (though it exists).

                Features

                Feature Description
                Scope Local to the function/block
                Lifetime During function execution
                Default Value Garbage value
                Memory RAM

                Example

                void fun() { auto int x = 10; // same as int x = 10; }

                Register Storage Class (register)

                • Suggests the compiler to store the variable in CPU registers (faster access).

                Features

                Feature Description
                Scope Local to the function/block
                Lifetime During function execution
                Default Value Garbage
                Memory CPU register (if available)

                Example

                void fun() { register int i; }

                You cannot use & operator on register variables

                & i ❌ // Not allowed

                Static Storage Class (static)

                • Static variables retain their value throughout the program execution.
                • Lifetime = whole program.

                  Features

                  Feature Description
                  Scope Local but value is retained between function calls
                  Lifetime Entire program execution
                  Default Value 0
                  Memory Static memory (global area)

                  Example

                  void fun() { static int x = 0; x++; printf("%d", x); }

                  If you call fun() 3 times, output will be:

                  1 2 3

                  (Unlike auto which resets every time)

                  External Storage Class (extern)

                  • Used to declare a global variable that is already defined somewhere else.

                  Features

                  Feature Description
                  Scope Global (accessible across multiple files)
                  Lifetime Entire program execution
                  Default Value 0
                  Memory Global memory

                  Example

                  File 1: int x = 10; // global definition

                  File 2: extern int x; // declaration

                  extern does not allocate memory, it only refers to an existing variable.

                  Summary Table: Storage Classes

                  Storage Class Keyword Scope Lifetime Default Value Memory
                  Automatic auto Local Function block only Garbage RAM
                  Register register Local Function block only Garbage CPU Register
                  Static static Local/Global Entire program 0 Static area
                  External extern Global Entire program 0 Global memory