[go: up one dir, main page]

0% found this document useful (0 votes)
43 views27 pages

Structures

structures

Uploaded by

Awez Parmar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views27 pages

Structures

structures

Uploaded by

Awez Parmar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Data Structures

CS2013

Dr. Shyamapada Mukherjee


Associate Professor

Department of Computer Science and Engineering


NIT Rourkela-769008, India

Lecture
August 5, 2025

1/27 Dr. Shyamapada Mukherjee Data Structures


Outline

What is a Structure? Pointers to Structures


Use of Structures Passing Structures to Functions
Structure vs Array Nested Structures
Structure and typedef Self-Referential Structures
Syntax of Structure Structure vs Union
Memory Layout Applications of Structures
Array of Structures Quiz

2/27 Dr. Shyamapada Mukherjee Data Structures


What is a Structure?
A user-defined data type in C.
Groups variables of different data types under one name.
Useful for representing real-world entities (e.g., student, book, employee).

Fig 1: Book Entity

3/27 Dr. Shyamapada Mukherjee Data Structures


Use of Structures
Organize complex data logically
Commonly used in:
Student/Employee Records
Linked Lists and Trees
File I/O Systems

Fig 2: Structure holding multiple data types

4/27 Dr. Shyamapada Mukherjee Data Structures


Structure vs Array
Feature Array Structure
Data Types Homogeneous (same type) Heterogeneous (different types)
Access Index-based (e.g., arr[0]) Member-name based (e.g., s.id)
Purpose Simple data collection Logical grouping of variables

Fig 3: Array-Same data type elements


Fig 4: Structure-Mixed data type elements

5/27 Dr. Shyamapada Mukherjee Data Structures


Structure Declaration and typedef in C
In C, a structure is declared using the struct keyword.
It groups related variables of different data types under one name.
The typedef keyword creates an alias (shortcut) for a structure.
This makes declarations simpler and improves code readability.

Syntax of defining a structure — with and without typedef:

Without typedef: With typedef:


struct Book { typedef struct {
int id ; int id ;
char title [100]; char title [100];
float price ; float price ;
}; } Book ;
struct Book b1 ; // Declaration using struct keyword Book b1 ; // Declaration using alias

6/27 Dr. Shyamapada Mukherjee Data Structures


Declaring and Initializing Structure Variables

Once a structure is defined, we can declare variables of that structure type.


There are two common ways to assign values:
Separate Declaration and Assignment: Declare the variable first, then assign values to its
members.
Initialization at Declaration: Provide values at the time of declaration itself.
Use functions like strcpy() to assign string values to character arrays inside the structure.
Proper initialization improves readability and reduces potential runtime errors.

Next: Code example showing both methods of initializing structure variables.

7/27 Dr. Shyamapada Mukherjee Data Structures


Defining and Initializing Variables
# include < stdio .h >
# include < string .h >

struct Book {
int id ;
char title [100];
float price ;
};

int main () {
// Method 1: Separate declaration and assignment
struct Book b1 ;
b1 . id = 101;
strcpy ( b1 . title , " C ␣ Programming " ) ;
b1 . price = 299.99;

// Method 2: Initialization at declaration


struct Book b2 = {102 , " Data ␣ Structures " , 350.50};

return 0;
}

8/27 Dr. Shyamapada Mukherjee Data Structures


Accessing Members of a Structure

Structure members are accessed using the dot (.) operator for regular variables.
Syntax: structureVariable.memberName
When using a pointer to a structure, members are accessed using the arrow operator: ->
Syntax: structurePointer->memberName
These operators allow reading from or assigning values to individual members.
Examples:
b1.id = 101; (dot operator)
ptr->price = 299.99; (arrow operator)

Next: Practical example of accessing members using the dot operator.

9/27 Dr. Shyamapada Mukherjee Data Structures


Accessing Structure Members

# include < stdio .h >

struct Book {
int id ;
char title [100];
float price ;
};

int main () {
struct Book b1 = {101 , " C ␣ Programming " , 299.99};

// Accessing structure members using dot operator


printf ( " ID : ␣ % d \ n " , b1 . id ) ;
printf ( " Title : ␣ % s \ n " , b1 . title ) ;
printf ( " Price : ␣ %.2 f \ n " , b1 . price ) ;

return 0;
}

10/27 Dr. Shyamapada Mukherjee Data Structures


Memory Layout of Structure

struct Test {
int id ; // 4 bytes
char name [10]; // 10 bytes
float salary ; // 4 bytes
};
// Expected total size : 18 bytes

Fig 5: Memory layout with possible padding between members

11/27 Dr. Shyamapada Mukherjee Data Structures


Array of Structures

An array of structures allows storing multiple records of the same structure type.
Useful for representing collections of similar objects, like students, employees, books, etc.
Each element of the array is a separate structure and accessed using array indexing.
Members of each structure element are accessed using the dot (‘.‘) operator.
Example Syntax:
struct Student class[10]; (Declares an array of 10 Student structures)
class[0].roll no = 1; (Accesses first student’s roll number)

Next: Code example of using an array of structures.

12/27 Dr. Shyamapada Mukherjee Data Structures


Array of Structures -Code

Figure: Array of Structure objects in memory


13/27 Dr. Shyamapada Mukherjee Data Structures
Memory Layout of Array of Structures

Figure: Memory Layout of Array of Structures


14/27 Dr. Shyamapada Mukherjee Data Structures
Pointers to Structures

A pointer to a structure stores the address of a structure variable.


Useful for dynamic memory allocation and efficient data manipulation.
Declare using: struct StructName *ptr;
Assign using: ptr = &variable;
Access members using the arrow operator (->) instead of the dot operator (.).
Example Syntax:
struct Student *ptr = &s1;
ptr->id = 101;

Next: Example program using pointer to a structure.

15/27 Dr. Shyamapada Mukherjee Data Structures


Pointers to Structures

# include < stdio .h >


# include < stdlib .h >

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

int main () {
struct Student s1 = {101 , " Bob " , 3.8};

// Pointer to structure
struct Student * ptr = & s1 ;

// Access members using arrow operator ( - >)


printf ( " ID :␣%d\n" , ptr -> id );
printf ( " Name :␣%s\n" , ptr -> name );
printf ( " GPA :␣ %.1 f\n" , ptr -> gpa );

return 0;
}

16/27 Dr. Shyamapada Mukherjee Data Structures


Guess the Output

# include < stdio .h >


# include < string .h >

struct Student {
char name [10];
int roll ;
float mark ;
};

int main () {
struct Student s1 ;
struct Student * ptr = & s1 ;

strcpy ( ptr -> name , " Alice ");


ptr - > roll = 25;
ptr - > mark = 87.5;

printf ( " Name :␣%s\n" , ptr -> name );


printf ( " Roll :␣%d\n" , ptr -> roll );
printf ( " Mark :␣ %.2 f\n" , ptr -> mark );

return 0;
}

17/27 Dr. Shyamapada Mukherjee Data Structures


Passing Structures to Functions

Structures in C can be passed to functions in two ways:


Pass by Value — A copy of the structure is passed. Changes inside the function do
not affect the original.
Pass by Reference (using pointers) — The memory address is passed. Changes
inside the function affect the original structure.
Use . (dot operator) with structure variables and -> (arrow operator) with
structure pointers.
Efficient to pass large structures using pointers to save memory and processing
time.

18/27 Dr. Shyamapada Mukherjee Data Structures


Example: Pass by Value and Reference

19/27 Dr. Shyamapada Mukherjee Data Structures


Nested Structures
Definition: A nested structure in C is a structure that contains another structure as a member.
It helps logically group related data like an address within an employee record.

Syntax and Access

struct Address {
char city [30];
int pin ;
};

struct Employee {
int id ;
struct Address addr ; // Nested structure
};

// Accessing nested members


struct Employee e ;
e . addr . pin = 123456; Fig 6: Nested Structure

20/27 Dr. Shyamapada Mukherjee Data Structures


Nested Structures

21/27 Dr. Shyamapada Mukherjee Data Structures


Self-Referential Structure

Definition: A self-referential structure is a structure that contains a pointer to a structure of


the same type. It forms the basis of dynamic data structures like linked lists, trees, and graphs.

Syntax:
struct Node {
char data ; // Stores data like ’A ’
struct Node * next ; // Pointer to the nextnode
};
Fig 7: self-referential structure

22/27 Dr. Shyamapada Mukherjee Data Structures


Self-Referential Structure - Example Code

23/27 Dr. Shyamapada Mukherjee Data Structures


Structure vs Union
Feature Structure Union
Memory Allocation Separate for each member Shared among members
Size Sum of all members Size of largest member
Access All members simultaneously One member at a time
Initialization All members can be initialized Only the first member

struct S {
int a ;
float b ;
}; // Typically 8 bytes

union U {
int a ;
float b ;
}; // Typically 4 bytes

24/27 Dr. Shyamapada Mukherjee Data Structures


Applications of Structures

Database Records: Student, employee, and inventory management.


Data Structures: Used in linked lists, trees, stacks, queues, graphs.
File Handling: Store and retrieve structured records from files.
Game Development: Represent characters, objects, and attributes.
Network Programming: Define packet headers and protocols.

25/27 Dr. Shyamapada Mukherjee Data Structures


Quiz Questions

1. What is the output of this code?

struct { char a ; int b ; } s ;


printf ( " % d " , sizeof ( s ) ) ;

2. How do you access members of a structure through a pointer?

3. What’s the difference between the following declarations?

struct Point { int x ; int y ; };


typedef struct { int x ; int y ; } Point ;

4. When would you use a union instead of a structure?

26/27 Dr. Shyamapada Mukherjee Data Structures


References

Karumanchi, N. Data Structures and Algorithms Made Easy: Data Structure and Algorithmic
Puzzles, 5thed., CareerMonk Publications, 2016. ISBN978-8193245279
https://ia601202.us.archive.org/8/items/data-structures-and-algorithms-narasimha-
karumanchi/Data
Schaum’s Outline of Data Structures, revised edition, SeymourLipschutz. New Delhi:
McGraw-Hill Education (India) Pvt Ltd, 2014. ISBN 978-1259029967
https://gnindia.dronacharya.info/IT/3rdSem/Downloads/DataStructure/Books/DATA-
STRUCTURE-BOOK-3.pdf

27/27 Dr. Shyamapada Mukherjee Data Structures

You might also like