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

ConceptMeaning
StructureUser-defined datatype
Access operatorDot .
Nested structureStructure inside structure
Array of structureMultiple items of same struct
Pointer to structureUses ->
Structure initializationUsing { } or assignment
Allowed operationsAssignment, function call
Not allowedStructure 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)

FeatureStructureUnion
MemoryEach member has separate memoryAll members share the same memory
SizeSum of all membersSize of the largest member
Simultaneous storageCan store all values at onceOnly one member at a time
Use CaseMultiple data needed togetherEfficient 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

FeatureDescription
ScopeLocal to the function/block
LifetimeDuring function execution
Default ValueGarbage value
MemoryRAM

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

FeatureDescription
ScopeLocal to the function/block
LifetimeDuring function execution
Default ValueGarbage
MemoryCPU 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

FeatureDescription
ScopeLocal but value is retained between function calls
LifetimeEntire program execution
Default Value0
MemoryStatic 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

FeatureDescription
ScopeGlobal (accessible across multiple files)
LifetimeEntire program execution
Default Value0
MemoryGlobal 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 ClassKeywordScopeLifetimeDefault ValueMemory
AutomaticautoLocalFunction block onlyGarbageRAM
RegisterregisterLocalFunction block onlyGarbageCPU Register
StaticstaticLocal/GlobalEntire program0Static area
ExternalexternGlobalEntire program0Global memory