Unit 3: Arrays



ARRAYS IN C 

An array is a collection of multiple values of the same data type, stored in contiguous (continuous) memory locations.

It allows storing many values under one variable name.

Example

int marks[5];

This creates space for 5 integers.

Array Notation and Representation

Every array has:

  • Name: identifier
  • Index: starts from 0
  • Elements: values stored inside
  • Size: number of elements

Example

int a[5] = {10, 20, 30, 40, 50};

Index mapping:

IndexValue
010
120
230
340
450

Memory is stored continuously.

Declaring a One-Dimensional Array

Syntax

data_type array_name[size];

Example

int num[10]; float price[50]; char grade[5];

Size must be a positive integer.

Initializing Arrays

You can assign initial values at the time of declaration.

A. Full Initialization

int a[5] = {1, 2, 3, 4, 5};

B. Partial Initialization

Remaining values become 0.

int a[5] = {10, 20};

C. Without specifying size

Compiler determines size.

int a[] = {1, 2, 3, 4};

D. String Initialization

Char arrays behave like strings.

char name[] = "Hello";

Accessing Array Elements

Use the index number.

Example

a[0] = 10; // store printf("%d", a[0]); // access

Manipulating Array Elements

You can update, modify, or process array values using loops.

Example: Adding 5 to every element

for (int i = 0; i < 5; i++) { a[i] += 5; }

Example: Searching for an element

for (int i = 0; i < n; i++) { if (a[i] == key) { printf("Found"); } }

Arrays of Unknown or Varying Size

A. Using user input

Size is given by user.

int n; scanf("%d", &n); int arr[n]; // allowed in C99 as Variable-Length Array (VLA)

B. Using dynamic memory (malloc)

For very large or flexible arrays.

int *arr = malloc(n * sizeof(int));

Two-Dimensional Arrays (2D Arrays)

2D arrays are like tables with rows and columns.

Syntax

data_type array_name[rows][columns];

Example

int matrix[3][3];

Initialization

int matrix[3][3] = { {1,2,3}, {4,5,6}, {7,8,9} };

Accessing Elements

printf("%d", matrix[1][2]); // prints 6

Multidimensional Arrays

Arrays with more than 2 dimensions (3D, 4D...).

Example of 3D Array

int box[2][3][4];

This means:

  • 2 tables
  • each table has 3 rows
  • each row has 4 columns

Accessing elements

box[1][2][3];

Difference Between 1D, 2D & Multi-D Arrays

TypeStructureExample
1DSingle rowint a[5]
2DTable (rows × columns)int b[3][3]
3D & aboveMultiple tablesint c[2][3][4]

Real-Life Uses of Arrays

AreaUse
Data scienceStoring datasets
MatricesMathematical operations
Image processingPixel representation (2D/3D arrays)
GamesStoring maps, scores
BankingCustomer records

Example Program (2D Array Sum)

#include <stdio.h> int main() { int a[2][2] = {{1,2},{3,4}}; int sum = 0; for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { sum += a[i][j]; } } printf("Sum = %d", sum); return 0; }

SUMMARY TABLE

ConceptExplanation
ArrayCollection of similar data
1D ArrayLinear structure
2D ArrayRow-column matrix
InitializationAssigning values
AccessingUsing index
ManipulationUpdating array values
VLAVariable Length Arrays
Multidimensional3D, 4D… arrays

POINTERS IN C 

Introduction to Pointers

A pointer is a variable that stores the memory address of another variable.

Example:

int a = 10; int *p = &a;

Here:

  • a → stores value 10
  • p → stores address of a
  • *p → gives value of a (dereferencing)

Why pointers are important?

  • Memory management
  • Dynamic allocation
  • Call by reference
  • Efficient array handling
  • Structures, linked lists, trees
  • Function pointers

Characteristics of Pointers

  1. Pointers store address, not value
  2. They consume fixed memory (usually 4 or 8 bytes)
  3. Pointer type must match the variable type
  4. Pointer arithmetic is possible (+, -, ++, --)
  5. Pointers are powerful but require careful usage

& and * Operators

& (Address-of operator)

Used to get the address of a variable.

int x = 5; printf("%p", &x); // prints address of x

* (Dereference operator)

Used to access the value stored at the address.

int x = 5; int *p = &x; printf("%d", *p); // prints 5

Pointer Type Declaration and Assignment

Declaration

int *p; float *q; char *c;

Assignment

int a = 20; p = &a; // pointer stores address of a

Pointers must be assigned addresses, not values.

Pointer Arithmetic

Valid operations for pointers:

OperationMeaning
p++Move to next memory location
p--Move to previous location
p + nJump forward n elements
p - nMove backward n elements

Example

int arr[3] = {10, 20, 30}; int *p = arr; // arr = &arr[0] printf("%d", *(p+1)); // prints 20

Pointer arithmetic jumps based on data type size.

For int (4 bytes):

  • p+1 → next 4-byte block

Call By Reference Using Pointers

C does not support call-by-reference directly.
But we can simulate it using pointers.

Example

void change(int *n) { *n = 50; } int main() { int a = 10; change(&a); printf("%d", a); // 50 }

Passing Pointers to Functions

Pointers allow functions to modify actual variables.

Example

void update(int *x) { *x += 10; }

Calling:

int n = 5; update(&n);

Array and Pointers

Arrays and pointers are closely related.

Example

int a[5] = {1,2,3,4,5}; int *p = a; // same as &a[0]

  • p[0] = 1
  • *(p+2) = 3

Array of Pointers

An array that stores addresses.

Example: array of strings

char *names[] = {"Ram", "Shyam", "Mohan"};

Example: array of integer pointers

int a = 10, b = 20, c = 30; int *arr[] = {&a, &b, &c};

Pointer to Pointer (Double Pointer)

A pointer that stores the address of another pointer.

Syntax

int **pp;

Example

int x = 5; int *p = &x; int **pp = &p; printf("%d", **pp); // prints 5

Pointer to Function

A pointer that stores the address of a function.

Syntax

return_type (*pointer_name)(parameter_list);

Example

int add(int x, int y) { return x + y; } int (*fptr)(int, int) = add; printf("%d", fptr(5, 10)); // 15

Uses:

  • Callbacks
  • Event handling
  • Dynamic function selection

Array of Function Pointers

Stores multiple function addresses.

Example

int add(int a, int b) { return a + b; } int sub(int a, int b) { return a - b; } int (*op[2])(int, int) = {add, sub}; printf("%d", op[0](5, 3)); // add → 8 printf("%d", op[1](5, 3)); // sub → 2

Summary Table

ConceptMeaning
PointerStores address
&Address-of
*Value-at-address
Pointer arithmeticMove to next/previous element
Passing pointerAllows modification in functions
Array of pointersStores multiple addresses
Pointer to pointerDouble-level addressing
Function pointerHolds function address

STRINGS IN C 

A string in C is a collection of characters stored in a character array and terminated with a null character \0.

Example:

char name[] = "India";

Internally stored as:

| I | n | d | i | a | \0 |

Important:
C does not have a built-in "string" data type.
Strings are handled using character arrays or char pointers.

Initializing Strings

A. Initialization using character array

char country[6] = {'I','n','d','i','a','\0'};

B. Initialization using string literal (easier)

char country[] = "India";

C. Initialize an empty string

char name[20] = "";

D. Without specifying size

Compiler decides size automatically.

char city[] = "Delhi";

Accessing String Elements

You use index numbers (0,1,2…) like with arrays.

Example:

char name[] = "Ram"; printf("%c", name[1]); // prints 'a'

You can also modify characters:

name[2] = 'n'; // "Ran"

Array of Strings

An array of strings means multiple strings stored together.

Method 1: Using 2D array

char cities[3][10] = {"Delhi", "Mumbai", "Goa"};

Memory representation:

| Delhi | Mumbai | Goa |

Method 2: Using array of char pointers

(More memory efficient)

char *cities[] = {"Delhi", "Mumbai", "Goa"};

Passing Strings to Functions

Strings are passed as character pointers because arrays decay to pointers.

Example:

void display(char str[]) { printf("%s", str); } int main() { char name[] = "Jay"; display(name); }

You can also use:

void display(char *str);

Common String Functions in C (string.h)

Include header:

#include <string.h>

1. strlen() — length of string

strlen("Hello"); // returns 5

2. strcpy() — copy string

strcpy(dest, src);

3. strcat() — concatenate two strings

strcat(str1, str2);

4. strcmp() — compare two strings

Returns:

  • 0 → strings are equal
  • <0 → str1 < str2
  • >0 → str1 > str2

strcmp("abc","abc"); // 0

5. strrev() — reverse a string

(Not available in all compilers)

strrev(str);

6. strlwr() / strupr() — lowercase / uppercase

Compiler dependent.

Example Program: Count Vowels in a String

#include <stdio.h> int main() { char str[50]; int i, count = 0; printf("Enter a string: "); gets(str); for (i = 0; str[i] != '\0'; i++) { if (str[i]=='a'||str[i]=='e'||str[i]=='i'||str[i]=='o'||str[i]=='u'|| str[i]=='A'||str[i]=='E'||str[i]=='I'||str[i]=='O'||str[i]=='U') { count++; } } printf("Vowels = %d", count); return 0; }

Example Program: Reverse a String Using Function

void reverse(char str[]) { int len = strlen(str); for(int i=0; i<len/2; i++) { char temp = str[i]; str[i] = str[len-i-1]; str[len-i-1] = temp; } } int main() { char s[20] = "hello"; reverse(s); printf("%s", s); // olleh }

Summary Table

TopicExplanation
StringCharacter array ending with \0
InitializationLiteral or char array
AccessingUsing index
Array of strings2D array or pointer array
Passing to functionPassed as pointer
String functionsstrlen, strcpy, strcat, strcmp, strrev