Module 1
Module 1
1. Arrays
1.1 Introduction
An array is a finite ordered collection of homogeneous data elements, stored in contiguous memory
locations. Arrays allow efficient element access through indexing and are suitable for storing large
datasets where random access is required.
A one-dimensional array is a list of elements of the same type accessed using a single index.
Declaration:
int marks[5];
Initialization:
marks[2] = 90;
Traversal Example:
printf("%d\n", marks[i]);
Declaration:
int mat[3][4];
Initialization:
int a[2][3][4];
1D Dynamic Array:
2D Dynamic Array:
Deallocation:
free(arr[i]);
free(arr);
2. Pointers
2.1 Introduction
A pointer is a variable that holds the address of another variable. Pointers enhance memory efficiency
and enable powerful features like dynamic memory allocation, function pointers, and linked data
structures.
int x = 10;
int *p = &x;
Example:
In arrays:
*(arr + i) == arr[i]
1. malloc(size_t size)
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr;
if (arr == NULL) {
return 1;
arr[i] = i + 1;
return 0;
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
if (arr == NULL) {
return 1;
free(arr);
return 0;
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
arr[i] = i + 1;
arr[i] = i + 1;
free(arr);
return 0;
4. free(void *ptr)
• Frees the memory space pointed to by ptr, which must have been returned by one of the
memory allocation functions.
• After using free, the pointer becomes a dangling pointer and should be set to NULL.
free(ptr);
ptr = NULL;
• Dangling Pointer: A pointer that refers to a memory location that has already been freed.
int *q = (int*)malloc(sizeof(int));
free(q);
*q = 20; // dangling pointer
3.1 Structures
typedef struct {
int id;
char name[30];
float salary;
} Employee;
typedef struct {
} Date;
typedef struct {
char name[20];
Date dob;
} Person;
Access:
Person p;
p.dob.day = 15;
Employee emp[5];
3.5 Unions
A union is similar to a structure, but all members share the same memory.
union Data {
int i;
float f;
char str[20];
};
Usage:
union Data d;
d.i = 10;
printf("%d", d.i);