Data Structure - Module-1 Notes
Data Structure - Module-1 Notes
data_type array_name[size];
Example:
type array_name[size1][size2][size3];
where:
•size1 → Number of layers.
•size2 → Number of rows per layer.
•size3 → Number of columns per row.
Example 3D Array
Representation:
Layer 1:
12
34
Layer 2:
56
78
What Does "Layers" Mean in Multi-Dimensional Arrays?
• In multi-dimensional arrays, a layer refers to a group of rows
and columns at a particular depth level.
• Think of it as stacking multiple 2D arrays on top of each
other to form a 3D structure.
• A 2D array is like a table with rows and columns. When you
extend this into 3D, you get multiple 2D arrays stacked
together, where each stack is called a layer.
• Initializing a Multidimensional Array
For example:
array[0][0][0] → (1st layer, 1st row, 1st column)
array[1][2][1] → (2nd layer, 3rd row, 2nd column)
array[2][1][2] → (3rd layer, 2nd row, 3rd column)
• Traversing a 3D Array
int i, j, k;
for(i = 0; i < 2; i++) {
for(j = 0; j < 2; j++) {
for(k = 0; k < 2; k++) {
printf("%d ", cube[i][j][k]); }
printf("\n"); }
printf("\n"); }
#include <stdio.h> // Displaying the 3D array
printf("3D Array
int main() { Representation:\n");
int data[2][3][3]; // 3D array with 2 for (int l = 0; l < 2; l++) {
layers, 3 rows, 3 columns printf("\n=== Layer %d ===\n", l
+ 1);
// Initializing the 3D array for (int r = 0; r < 3; r++) {
int value = 1; for (int c = 0; c < 3; c++) {
for (int l = 0; l < 2; l++) { // Layers printf("%d ", data[l][r][c]);
for (int r = 0; r < 3; r++) { // Rows }
for (int c = 0; c < 3; c++) {// printf("\n"); // New line after
Columns each row
data[l][r][c] = value++; }
} }
}
} return 0;
}
• Use Cases of 3D Arrays
[Link] Imaging (CT Scans, MRI Scans)
1. Used to store 3D medical scans, where each slice is a 2D image.
2.3D Graphics and Computer Vision
1. Used for storing RGB color images (each pixel has Red, Green, Blue
values).
• int image[1920][1080][3]; // RGB image storage
4D Array
int main() {
char word[] = "Hello";
printf("String: %s\n", word);
return 0;
}
Output:
String: Hello // %s prints characters until \0 is
found.
Pointers in C
Introduction to Pointers
• A pointer is a variable that stores the memory address of another
variable. Instead of storing values directly, it stores the location
(address) of the value in memory.
Declaration of a Pointer
data_type *pointer_name;
Here *(asterisk) denotes a pointer. data_type specifies the type of data
it points to.
Example
int *ptr; // Pointer to an integer
char *cptr; // Pointer to a character
float *fptr; // Pointer to a float
Pointer Concepts
• Address-of operator (&): Gets the memory address of a variable.
• Dereference operator (*): Accesses the value stored at the pointer’s address.
#include <stdio.h>
int main() {
int num = 10;
int *ptr = # // Pointer stores the address of Output:
num Value of num: 10
printf("Value of num: %d\n", num); Address of num:
printf("Address of num: %p\n", &num); 0x7ffeefbff6dc
printf("Pointer stores: %p\n", ptr); Pointer stores: 0x7ffeefbff6dc
printf("Value accessed via pointer: %d\n", *ptr); // Value accessed via pointer:
Dereferencing 10
return 0;
}
Accessing Variables through Pointers
• A pointer allows you to modify the value of a variable indirectly.
#include <stdio.h>
int main() {
int x = 5; Output:
int *ptr = &x; Before: x = 5
printf("Before: x = %d\n", x); After: x = 20
*ptr = 20; // Changing value via pointer
printf("After: x = %d\n", x);
return 0;
}
Pointer Applications
(A) Arrays and Pointers
• An array name itself acts as a pointer to the first element.
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30}; Output:
int *ptr = arr; // Pointer to the first First element: 10
element Second element: 20
printf("First element: %d\n", *ptr); Third element: 30
printf("Second element: %d\n", *(ptr +
1));
printf("Third element: %d\n", *(ptr + 2));
return
• arr is not0; }
a variable, but a constant pointer to the first element of the array.
• The expression arr already holds the memory address of arr[0].
• Ie arr represents the address of the first element (&arr[0]).
B. Pointer to Function
Pointers can be used to call functions dynamically.
Memory Layout of a C- program
• When a C program runs, it requires memory allocation in RAM
(Random Access Memory).
• The operating system (OS) assigns memory to the program in
a structured manner, dividing it into segments.
What is a Function Pointer?
• A function pointer is a pointer that stores the memory address of
a function instead of a variable. It allows functions to be called
dynamically.
Memory Representation of a Function
When a function is declared/defined in C:
void display() {
printf("Hello from function pointer!\n"); }
return 0;
}
Dynamic Memory Allocation
functions in C
What is Dynamic Memory Allocation
• Dynamic Memory Allocation allows memory to be allocated
at runtime instead of compile time. This is useful when we
don’t know the exact memory size needed beforehand.
• Memory is allocated in the heap section.
• Returns the address of the allocated memory's first byte to
a pointer.
• All these functions are found in the <stdlib.h> library.
• Must be deallocated using free() to avoid memory loss after
use.
Functions for Dynamic Memory Allocation
malloc() – Memory Allocation
#include <stdio.h>
#include <stdlib.h>
int main() {
float *ptr; // Declare a pointer to float
ptr = (float*) malloc(sizeof(float)); // Allocate memory for 1 float
if (ptr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
*ptr = 3.14; // Storing a float value in allocated memory
printf("Stored float value: %.2f\n", *ptr);
printf("Memory address allocated: %p\n", ptr); // Print memory address
return 0; }
Output: Stored float value: 3.14
Memory address allocated: 0x600003e71 (Example address)
calloc() – Contiguous Allocation
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr, i; malloc()
arr = (int*) calloc(5, sizeof(int)); // Allocates memory for 5 integers does not
if (arr == NULL) { initialize
printf("Memory allocation failed!\n"); memory,
return 1;
but calloc()
}
printf("Array elements after calloc(): "); sets all
for (i = 0; i < 5; i++) { values to
printf("%d ", arr[i]); // All elements should be 0 0.
}
return 0;}
return 0; }
ptr[i] is equivalent to *(ptr + i)
free() – Deallocate Memory
• Syntax
free(ptr);
ptr = NULL; // Avoids dangling pointer issues
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int*) malloc(sizeof(int));
if (ptr == NULL) {
printf("Memory allocation failed!\n");
return 1;
}
*ptr = 55;
printf("Value stored: %d\n", *ptr);
return 0;}
Structures and Unions
In C programming, structures and unions allow grouping multiple
variables of different types under one name.
Introduction to Structures
✔ A structure (struct) is a user-defined data type that allows
storing multiple variables of different types together.
✔ Useful for representing real-world entities (e.g., student
details, employee records).
Declaring a Structure
✔ We define a structure using the ‘struct’ keyword.
#include <stdio.h>
// Define a structure
struct Student {
int roll_no;
char name[50];
float marks;
};
int main() {
struct Student s1; // Declaring a
structure variable
return 0;
}
int main() {
// Initialization
struct Student s1 = {101, "John Doe",
89.5};
printf("Roll No: %d\n", s1.roll_no);
Order matters! {101, "John Doe", 89.5} printf("Name: %s\n", [Link]);
matches {int, char[], float}. printf("Marks: %.2f\n", [Link]);
return 0;
Comparison of #include <stdio.h>
#include <string.h>
return 0;
}
Arrays of Structures
#include <stdio.h>
struct Student {
• A structure can be int roll_no;
char name[50];
used as an array to float marks;
store multiple records. };
return 0;}
Arrays Within
Structures Example: Storing Multiple Subjects' Marks
#include <stdio.h>
return 0;
}
Nested Example: Student with Address Structure
#include <stdio.h>
Structures struct Address {
char city[50];
• A structure inside char state[50];
};
another structure.
• Allows better struct Student {
organization of complex int roll_no;
char name[50];
data structures. struct Address address; // Nested Structure
};
int main() {
struct Student s1 = {101, "John Doe", {"New York",
"NY"}};
#include <stdio.h>
s union Data {
int i;
• A union is similar float f;
to a structure, but char str[20];
all members share };
the same memory
int main() {
location. union Data data;
• Saves memory
but only one data.i = 10;
member can store printf("Integer: %d\n", data.i);
a value at a time.
data.f = 3.14; // Overwrites previous value
• Each assignment printf("Float: %.2f\n", data.f);
overwrites the
previous value. strcpy([Link], "Hello"); // Overwrites previous value
printf("String: %s\n", [Link]);
return 0; }
Example: Checking Size of Structure
Size of Structures
#include <stdio.h>
struct Test {
char a;
int b;
• The size of a double c;
structure depends };
on padding &
alignment. int main() {
printf("Size of struct: %lu bytes\n",
• Due to memory sizeof(struct Test));
alignment, the return 0;
}
structure may take
more space than • sizeof() is an operator that returns the size in bytes of