Concept of Structure and Union: defining, declaring, initializing, accessing

A struct bundles DIFFERENT types into one record (struct student: roll, name, marks, grade), accessed with the dot operator; a union looks identical but its members SHARE one memory space, one at a time.

12 min read · 11 cards · 3 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

The finale the subject promised

Look at the marks program's data, scattered like luggage: roll numbers in one array, names in a char grid, marks in another array, grades in a fourth. Student 17 is a COINCIDENCE of four index-17s. Sort one array and forget the others, and Riya gets Aman's grade.

What reality wants is one record: THIS roll, THIS name, THESE marks, travelling together.

C's answer is the struct, the final and most job-relevant idea in this subject.

Theory

One file per student

A college office does not keep one register of everyone's rolls, another of everyone's names, a third of marks. It keeps one FILE per student with every detail inside, and a cupboard of such files. The struct is the file (mixed contents, one cover); the array of structs is the cupboard. An array said "60 boxes, same type"; a struct says "one bundle, DIFFERENT types". Together they model anything.

Theory

Define, declare, initialize, access

Define the type (a template, NO memory yet):

struct student {

int roll;

char name[20];

int marks;

char grade;

};

Declare variables (memory now): struct student s1;

Initialize: struct student s1 = {42, "Riya", 78, 'A'};

Access with the dot: s1.marks = 92; printf("%s", s1.name); and for the name member, strcpy(s1.name, "Riya") (arrays refuse =, as always).

Practical

The marks program, final form

#include <stdio.h>

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

int main() {
    struct student klass[3] = {
        {1, "Riya", 78, 'A'},
        {2, "Aman", 55, 'B'},
        {3, "Zoya", 91, 'A'}
    };
    int i;
    for (i = 0; i < 3; i++)
        printf("%d %-6s %3d  %c\n", klass[i].roll,
               klass[i].name, klass[i].marks, klass[i].grade);
    return 0;
}

This example runs in Gri-Learn on the web, where you can edit it and see the output.

Quiz

struct student { int roll; char name[20]; int marks; char grade; }; This definition alone reserves how much memory?

  1. None: a definition is a template; memory arrives with variable declaration
  2. 29 bytes immediately
  3. One byte for the semicolon
  4. 20 bytes for the name array
Show the answer

None: a definition is a template; memory arrives with variable declaration

Defining a struct teaches C a new TYPE, a stencil, and stencils occupy nothing. Memory is allocated per VARIABLE: struct student s1; carves the actual bytes (roughly the members' sum, plus alignment padding). "Does the definition allocate memory?" is a fixture of theory papers, and the answer is a firm no.

Think first

Sort WITHOUT losing anyone

Remember bubble sort's swap with temp? In the struct world, how do you sort the class by marks so that names and grades travel WITH their marks? What is the swap's temp?

Show the answer

Swap whole records: struct student temp = klass[j]; klass[j] = klass[j+1]; klass[j+1] = temp;, structs, unlike arrays, DO allow = assignment, copying every member at once. The parallel-arrays bug (Riya getting Aman's grade) becomes impossible: the file moves as one. This struct-sort is the marks program's graduation exam, and a real lab question.

Theory

The union: same syntax, shared room

Swap the keyword and something radical happens:

union value {

int i;

float f;

char c;

};

A union's members all share ONE memory block, sized for the largest member. Write u.i = 65, and u.f and u.c are looking at the SAME bytes: write u.f = 2.5 and u.i is overwritten, garbage. One drawer with relabelled contents: one member alive at a time. Its purpose: saving memory when a value is only ever ONE of several types (embedded systems, variant records).

Quiz

union value u; u.i = 100; u.f = 2.5; printf("%d", u.i); What prints?

  1. Garbage: writing u.f overwrote the shared bytes that held 100
  2. 100: each member keeps its own storage
  3. 2: u.f rounds into u.i
  4. 102: the members add up
Show the answer

Garbage: writing u.f overwrote the shared bytes that held 100

One room, one occupant: u.f moved in and u.i's 100 was demolished; reading u.i now reinterprets float bytes as an int, garbage. In a STRUCT both members have their own rooms and 100 would survive. This overwrite trace is THE union exam question, and the sharpest struct-vs-union demonstration.

Watch out

Where marks leak

Forgetting the semicolon after the closing brace of a struct definition: a famously confusing error cascade. Dot on the wrong thing: klass.marks is wrong, klass[i].marks is right, the array element is the struct. = on the name member: s1.name = "Riya" fails (array!), strcpy it. Union carelessness: only the LAST-written member is readable; reading another is garbage, not error.

Theory

You are one keyword from a database

Look at struct student and squint: roll, name, marks, grade... that is a database ROW, and klass[60] is a TABLE. BCA105's SQL will hand you the same idea with a query language on top, and every backend job you will ever hold moves records like these. Next lesson closes the subject: struct vs union, formally, in the comparison table exams demand.

Summary

Key takeaways

  • A struct bundles DIFFERENT types into one record type; definition allocates nothing.
  • Declare for memory, initialize with {}, access members with the dot: s1.marks.
  • Arrays of structs (klass[60]) are the marks program's true form; structs allow = for whole-record copy.
  • strcpy for char-array members; never = on them.
  • A union's members SHARE one memory block (size of largest): one alive at a time.
  • Writing one union member corrupts the others, struct members live separately.
  • Memory hook: one file per student; the union is one drawer, relabelled.

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Functions and Structure

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

Concept of Structure and Union: defining, declaring, initializing, accessing · Computer Programming and Programming Methodology (CPPM) · Gri-Learn