Lecture 19: Pointers to Arrays, Structures & Functions

Unit IV: Structures and Pointers

Dr. Mohsin Dar | Cloud & Software Operations Cluster | UPES

Topics Covered Today:

  • Pointers to Arrays - Array-pointer relationship and manipulation
  • Pointers to Structures - Dynamic structure handling
  • Pointers to Functions - Callback mechanisms and function references
Building on Previous Lecture: We'll extend our pointer knowledge to work with complex data types!

Pointer to Arrays - Introduction

An array name acts as a constant pointer to the first element of the array.

Key Concepts:

  • Array Name is a pointer constant to the first element
  • &arr[0] and arr give the same address
  • arr[i] is equivalent to *(arr + i)
  • We can use pointers to traverse arrays efficiently
int arr[5] = {10, 20, 30, 40, 50}; int *ptr = arr; // ptr points to first element printf("arr = %p\n", arr); printf("&arr[0] = %p\n", &arr[0]); printf("ptr = %p\n", ptr);

Array in Memory

Memory Layout of Array:

int arr[5] = {10, 20, 30, 40, 50};
10
20
30
40
50
Address
1000
Address
1004
Address
1008
Address
1012
Address
1016
Note: Addresses increment by 4 bytes (size of int) in contiguous memory

Accessing Array Elements via Pointers

Multiple Ways to Access:

Method Syntax Description
Array Subscript arr[i] Traditional array notation
Pointer Arithmetic *(arr + i) Pointer offset from base
Pointer Variable *(ptr + i) Using separate pointer
Pointer Subscript ptr[i] Array notation on pointer
int arr[3] = {100, 200, 300}; int *ptr = arr; printf("%d\n", arr[1]); // Output: 200 printf("%d\n", *(arr + 1)); // Output: 200 printf("%d\n", *(ptr + 1)); // Output: 200 printf("%d\n", ptr[1]); // Output: 200

Complete Example: Traversing Array

#include <stdio.h> int main() { int arr[5] = {10, 20, 30, 40, 50}; int *ptr = arr; printf("Using array notation:\n"); for(int i = 0; i < 5; i++) { printf("arr[%d] = %d\n", i, arr[i]); } printf("\nUsing pointer arithmetic:\n"); for(int i = 0; i < 5; i++) { printf("*(ptr + %d) = %d\n", i, *(ptr + i)); } printf("\nUsing pointer increment:\n"); for(int i = 0; i < 5; i++) { printf("*ptr = %d\n", *ptr); ptr++; // Move to next element } return 0; }

Pointer to Structures

Pointers to structures allow dynamic memory allocation and efficient passing of structures to functions.

Syntax:

struct Student { char name[50]; int roll; float marks; }; struct Student s1; struct Student *ptr = &s1; // Pointer to structure

Accessing Members:

  • (*ptr).member - Dereference then access
  • ptr->member - Arrow operator (preferred)

Structure Pointer: Arrow Operator

struct Student { char name[50]; int roll; float marks; }; struct Student s1 = {"Rahul", 101, 85.5}; struct Student *ptr = &s1; // Method 1: Using dereference operator printf("Name: %s\n", (*ptr).name); printf("Roll: %d\n", (*ptr).roll); // Method 2: Using arrow operator (Recommended) printf("Name: %s\n", ptr->name); printf("Roll: %d\n", ptr->roll); printf("Marks: %.2f\n", ptr->marks);
Important: The arrow operator (->) is syntactic sugar for (*ptr).member

Structure Pointer Visualization

struct Student { char name[50]; int roll; float marks; }; struct Student s1 = {"Rahul", 101, 85.5}; struct Student *ptr = &s1;
ptr
2000
Address of s1
s1 (Address: 2000)
name: "Rahul"
roll: 101
marks: 85.5

Complete Example: Structure Pointer

#include <stdio.h> #include <string.h> struct Student { char name[50]; int roll; float marks; }; void displayStudent(struct Student *ptr) { printf("\n--- Student Details ---\n"); printf("Name: %s\n", ptr->name); printf("Roll: %d\n", ptr->roll); printf("Marks: %.2f\n", ptr->marks); } int main() { struct Student s1; struct Student *ptr = &s1; strcpy(ptr->name, "Priya Sharma"); ptr->roll = 102; ptr->marks = 92.5; displayStudent(ptr); return 0; }

Dynamic Memory Allocation for Structures

Using malloc() to create structures dynamically at runtime
#include <stdio.h> #include <stdlib.h> struct Student { char name[50]; int roll; float marks; }; int main() { struct Student *ptr; // Allocate memory dynamically ptr = (struct Student*)malloc(sizeof(struct Student)); if(ptr == NULL) { printf("Memory allocation failed!\n"); return 1; } // Use the allocated structure ptr->roll = 103; ptr->marks = 88.0; printf("Roll: %d, Marks: %.2f\n", ptr->roll, ptr->marks); // Free allocated memory free(ptr); return 0; }
Remember: Always free dynamically allocated memory to prevent memory leaks!

Pointer to Functions

Function pointers store the address of a function and can be used to call functions indirectly.

Why Use Function Pointers?

  • Callback Functions - Pass functions as arguments
  • Event Handling - Register function handlers
  • Dynamic Function Selection - Choose function at runtime
  • Implementing Function Tables - Menu-driven programs
// Syntax for function pointer declaration return_type (*pointer_name)(parameter_types); // Example: int (*funcPtr)(int, int);

Declaring and Using Function Pointers

#include <stdio.h> // Function declaration int add(int a, int b) { return a + b; } int main() { // Declare function pointer int (*funcPtr)(int, int); // Assign function address to pointer funcPtr = add; // or funcPtr = &add; // Call function using pointer int result = funcPtr(10, 20); // or (*funcPtr)(10, 20); printf("Result: %d\n", result); // Output: 30 return 0; }
Note: Both funcPtr(a, b) and (*funcPtr)(a, b) are valid ways to call through a function pointer.

Function Pointer - Memory Visualization

int add(int a, int b) { return a + b; } int (*funcPtr)(int, int) = add;
funcPtr
0x4000A0
Points to add()
Function: add()
Address: 0x4000A0
int add(int a, int b) {
  return a + b;
}
Function names are actually pointers to the function code in memory!

Passing Function Pointers as Arguments

Callback Functions Example:

#include <stdio.h> int add(int a, int b) { return a + b; } int subtract(int a, int b) { return a - b; } int multiply(int a, int b) { return a * b; } // Function that takes function pointer as parameter void calculate(int x, int y, int (*operation)(int, int)) { int result = operation(x, y); printf("Result: %d\n", result); } int main() { calculate(10, 5, add); // Output: 15 calculate(10, 5, subtract); // Output: 5 calculate(10, 5, multiply); // Output: 50 return 0; }

Array of Function Pointers

Create a lookup table of functions for menu-driven programs
#include <stdio.h> int add(int a, int b) { return a + b; } int subtract(int a, int b) { return a - b; } int multiply(int a, int b) { return a * b; } int divide(int a, int b) { return a / b; } int main() { // Array of function pointers int (*operations[4])(int, int) = {add, subtract, multiply, divide}; int choice, a = 20, b = 4; printf("Choose: 0-Add, 1-Sub, 2-Mul, 3-Div: "); scanf("%d", &choice); if(choice >= 0 && choice < 4) { int result = operations[choice](a, b); printf("Result: %d\n", result); } return 0; }

Practical Application: Calculator

#include <stdio.h> int add(int a, int b) { return a + b; } int sub(int a, int b) { return a - b; } int mul(int a, int b) { return a * b; } int div(int a, int b) { return b != 0 ? a / b : 0; } int main() { int (*calc[4])(int, int) = {add, sub, mul, div}; char *ops[] = {"Addition", "Subtraction", "Multiplication", "Division"}; int a, b, choice; printf("Enter two numbers: "); scanf("%d %d", &a, &b); printf("\nSelect operation:\n"); for(int i = 0; i < 4; i++) printf("%d. %s\n", i, ops[i]); scanf("%d", &choice); if(choice >= 0 && choice < 4) printf("Result: %d\n", calc[choice](a, b)); return 0; }

Comparison: Pointer Types

Feature Pointer to Array Pointer to Structure Pointer to Function
Declaration int *ptr = arr; struct S *ptr; int (*ptr)(int);
Access *(ptr + i) or ptr[i] ptr->member ptr(args)
Arithmetic Allowed Allowed Not Allowed
Primary Use Array traversal Dynamic structures Callbacks
Memory Contiguous Single block Code segment
Key Takeaway: Each pointer type serves different purposes but follows similar principles of indirection.

Common Mistakes to Avoid

1. Array Pointers:

// WRONG: Modifying array name int arr[5]; arr++; // ERROR! Array name is constant pointer // CORRECT: Use a separate pointer int *ptr = arr; ptr++; // OK

2. Structure Pointers:

// WRONG: Using dot operator with pointer struct Student *ptr; ptr.roll = 10; // ERROR! // CORRECT: Use arrow operator ptr->roll = 10; // OK

3. Function Pointers:

// WRONG: Incorrect declaration int *funcPtr(int); // This is a function returning int* // CORRECT: Use parentheses int (*funcPtr)(int); // Pointer to function

Real-World Applications

🎯 Pointer to Arrays:

  • Image processing (2D arrays for pixels)
  • Matrix operations in scientific computing
  • Efficient array manipulation in algorithms

🎯 Pointer to Structures:

  • Linked lists, trees, graphs
  • Database record management
  • Dynamic data structures
  • Object-oriented programming in C

🎯 Pointer to Functions:

  • Event-driven programming (GUI callbacks)
  • Sorting with custom comparison functions
  • Plugin architectures
  • State machines and strategy patterns

Summary

Today we explored advanced pointer concepts that form the foundation of complex C programming!

Key Concepts Covered:

  • Pointer to Arrays: Array names are pointers; use pointer arithmetic for traversal
  • Pointer to Structures: Use -> operator; enables dynamic memory allocation
  • Pointer to Functions: Store function addresses; enable callbacks and dynamic dispatch
// Quick Reference: int *arrPtr = array; // Array pointer struct S *sPtr = &structure; // Structure pointer int (*fPtr)(int) = function; // Function pointer arrPtr[i]; // Access array element sPtr->member; // Access structure member fPtr(arg); // Call function
Next Lecture: We'll explore dynamic memory management and advanced data structures!

Practice Questions

Try These:

Question 1: Write a program to find the sum of array elements using pointer arithmetic.
Question 2: Create a structure for Employee (name, id, salary) and write functions to input and display employee data using structure pointers.
Question 3: Implement a simple calculator using an array of function pointers that supports 5 operations: +, -, *, /, %.
Assignment: Combine all three concepts - Create a program that manages student records (structure) in an array, and provides a menu using function pointers!

Thank You!

Questions & Discussion

💻

Lecture 19 Complete

Dr. Mohsin Dar
Assistant Professor
Cloud & Software Operations Cluster | SOCS
UPES
"Master Pointers, Master C Programming!"
1 / 22