Tuesday, 6 January 2026

Pointers and Functions in C++


Pointers and Functions in C++
Pointers play an important role in function calling, memory efficiency, and data sharing in C++. They allow functions to access and modify actual variables.

1. Passing Pointers to Functions (Call by Address)
When we pass a pointer to a function, the function can modify the original variable.

Example
#include <iostream>
using namespace std;
void change(int *p) 
{
    *p = 50;
}
int main() 
{
    int a = 10;
    change(&a);
    cout << a;   // Output: 50
    return 0;
}
✔ Here, the address of a is passed, so the value is changed permanently.

2. Passing Arrays to Functions
An array name acts as a pointer to the first element.

Example
void display(int *arr, int n) 
{
    for(int i = 0; i < n; i++)
        cout << *(arr + i) << " ";
}
Call:
int a[5] = {1, 2, 3, 4, 5};
display(a, 5);

3. Function Returning a Pointer
A function can return a pointer, but it must not return the address of a local variable.

Correct Example
int* larger(int *a, int *b) 
{
    if (*a > *b)
        return a;
    else
        return b;
}
Incorrect Example ❌
int* fun() {
    int x = 10;
    return &x;   // ❌ local variable
}

4. Pointers to Functions (Function Pointers)
A function pointer stores the address of a function.

Syntax
return_type (*pointer_name)(parameter_list);

Example
#include <iostream>
using namespace std;
int add(int a, int b) 
{
    return a + b;
}
int main() 
{
    int (*fp)(int, int) = add;
    cout << fp(3, 4);   // Output: 7
    return 0;
}

5. Pointer Parameters for Multiple Results
Using pointers, a function can return more than one value.

Example
void calc(int a, int b, int *sum, int *prod) 
{
    *sum = a + b;
    *prod = a * b;
}

6. Call by Value vs Call by Address
Feature             Call by Value         Call by Address
Data passed     Copy                         Address
Original value    Not changed         Changed
Uses pointer                              

7. Example Program (Exam-Friendly)
#include <iostream>
using namespace std;
void swap(int *x, int *y) 
{
    int temp = *x;
    *x = *y;
    *y = temp;
}
int main() 
{
    int a = 5, b = 10;
    swap(&a, &b);
    cout << a << " " << b;   // 10 5
    return 0;
}

8. Key Points for Exams
  • Pointers allow call by address
  • Arrays are passed as pointers
  • Functions can return pointers
  • Function pointers store function addresses
  • Useful for efficiency and memory management
Passing a function to another function in C++
In C++, a function can be passed to another function using a function pointer (and in modern C++, also using std::function or lambdas). This is useful for callbacks, custom operations, and flexible program design.

1. Using Function Pointers (Most Common – Exam Oriented)
Syntax
return_type (*func_ptr)(parameter_list);

Example 1: Passing Function as Argument
#include <iostream>
using namespace std;
int add(int a, int b) 
{
    return a + b;
}
int subtract(int a, int b) 
{
    return a - b;
}
void operate(int x, int y, int (*op)(int, int)) {
    cout << op(x, y) << endl;
}
int main() 
{
    operate(10, 5, add);       // Output: 15
    operate(10, 5, subtract);  // Output: 5
    return 0;
}

✔ Here, add and subtract are passed as arguments to operate().

2. How It Works (Concept)
  • Function name → address of function
  • Passed function → stored in function pointer
  • Function pointer → used to call the function
  • op(x, y);   // calls the passed function
3. Passing Functions with typedef (Simpler Syntax)
typedef int (*Operation)(int, int);
void operate(int a, int b, Operation op) 
{
    cout << op(a, b);
}

4. Passing Lambda Functions (Modern C++)
#include <iostream>
using namespace std;
void operate(int a, int b, int (*op)(int, int)) {
    cout << op(a, b);
}
int main() 
{
    operate(6, 3, [](int x, int y) { return x * y; });
    return 0;
}

✔ Lambdas without captures can be used as function pointers.

5. Using std::function (Advanced & Flexible)
#include <iostream>
#include <functional>
using namespace std;
void operate(int a, int b, function<int(int,int)> op)
{
    cout << op(a, b);
}
int main() {
    operate(8, 4, [](int x, int y) { return x / y; });
    return 0;
}

✔ Allows lambdas with captures.

6. Real-Life Example: Callback Function
#include <iostream>
using namespace std;
void success() 
{
    cout << "Operation Successful";
}
void process(void (*callback)()) 
{
    callback();
}
int main() 
{
    process(success);
    return 0;
}

7. Key Points (For Exams)
  • Function name represents its address
  • Functions are passed using function pointers
  • Syntax must match return type and parameters
  • Used for callbacks and flexible logic
  • std::function provides more flexibility (C++11+)
Pointers and Arrays in C++
In C++, pointers and arrays are closely related. An array name itself behaves like a pointer to its first element, which allows efficient data access and manipulation.

1. Relationship Between Arrays and Pointers
  • Array name stores the base address of the array
  • Pointer can store the address of an array element
int a[5] = {10, 20, 30, 40, 50};
int *p = a;   // same as &a[0]

✔ p points to the first element of the array.

2. Accessing Array Elements Using Pointers
Using Pointer Arithmetic
cout << *(p + 2);   // Output: 30

Using Array Notation
cout << a[2];       // Output: 30

✔ Both give the same result.

3. Pointer Arithmetic with Arrays
for(int i = 0; i < 5; i++) 
{
    cout << *(a + i) << " ";
}

Explanation:
  • a + i → address of ith element
  • *(a + i) → value at that address
4. Difference Between Array Name and Pointer
Array                             Pointer
Fixed size                     Can change address
Cannot be reassigned     Can be reassigned
Stores base address             Stores any address

a = p;   // ❌ invalid
p = a;   // ✔ valid

5. Arrays Passed to Functions as Pointers
void display(int *arr, int n) 
{
    for(int i = 0; i < n; i++)
        cout << arr[i] << " ";
}
Call:
int a[4] = {1, 2, 3, 4};
display(a, 4);

6. Pointer to an Array
int (*ptr)[5];
int a[5];
ptr = &a;

✔ ptr points to the entire array, not just one element.

7. Array of Pointers
int a = 10, b = 20, c = 30;
int *arr[3] = {&a, &b, &c};

cout << *arr[1];   // Output: 20

8. Character Arrays and Pointers
char str[] = "Hello";
char *p = str;
cout << p;   // Hello

9. Example Program (Exam-Oriented)
#include <iostream>
using namespace std;
int main() {
    int a[3] = {5, 10, 15};
    int *p = a;

    for(int i = 0; i < 3; i++) {
        cout << *(p + i) << " ";
    }
    return 0;
}
Output:
5 10 15

10. Key Points for Exams
  • Array name acts as a constant pointer
  • a[i] is equivalent to *(a + i)
  • Pointer arithmetic depends on data type
  • Arrays are passed to functions as pointers
  • Pointers improve efficiency
Pointer and one dimensional array in C++
In C++, one-dimensional arrays and pointers are closely related. Understanding this relationship is very important for exams and programming efficiency.

1. Basic Relationship
A one-dimensional array name represents the address of its first element.

int a[5] = {10, 20, 30, 40, 50};
int *p = a;        // same as &a[0]

✔ p points to the first element of array a.

2. Accessing Array Elements Using Pointer
Using Pointer Arithmetic
cout << *(p + 3);   // Output: 40

Using Array Index
cout << a[3];       // Output: 40

✔ Both are equivalent.

3. Equivalence of Array and Pointer Notation
Expression             Meaning
a[i]                             *(a + i)
p[i]                             *(p + i)

Example:
cout << p[2];   // Output: 30

4. Traversing 1-D Array Using Pointer
#include <iostream>
using namespace std;
int main() 
{
    int a[4] = {2, 4, 6, 8};
    int *p = a;
    for(int i = 0; i < 4; i++) 
{
        cout << *(p + i) << " ";
    }
    return 0;
}
Output:
2 4 6 8

Pointer and multidimensional array in C++
In C++, pointers are also used to access multidimensional arrays (like 2-D or 3-D arrays). The concept is slightly more advanced than one-dimensional arrays because we deal with rows and columns.

1. Two-Dimensional Array Memory Layout
A 2-D array is stored in row-major order in memory.

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

Memory sequence:

1  2  3  4  5  6

2. Pointer to a Multidimensional Array
For a 2-D array:

int a[2][3];
int (*p)[3] = a;

✔ p is a pointer to an array of 3 integers (one row).

3. Accessing Elements Using Pointer
cout << *(*(p + 1) + 2);

Explanation:
  • p + 1 → address of 2nd row
  • *(p + 1) → 2nd row
  • + 2 → 3rd column
  • *(*(p + 1) + 2) → element a[1][2]
4. Relation Between Array and Pointer Notation
Array Notation Pointer Notation
a[i][j]                 *(*(a + i) + j)

5. Traversing a 2-D Array Using Pointer
#include <iostream>
using namespace std;
int main() {
    int a[2][3] = { {1, 2, 3}, {4, 5, 6} };
    int (*p)[3] = a;

    for(int i = 0; i < 2; i++) {
        for(int j = 0; j < 3; j++) {
            cout << *(*(p + i) + j) << " ";
        }
        cout << endl;
    }
    return 0;
}
Output:
1 2 3
4 5 6

6. Passing Multidimensional Array to Function
Method 1: Specify Column Size
void display(int a[][3], int r) 
{
    for(int i = 0; i < r; i++)
        for(int j = 0; j < 3; j++)
            cout << a[i][j] << " ";
}

Method 2: Using Pointer
void display(int (*p)[3], int r) 
{
    for(int i = 0; i < r; i++)
        for(int j = 0; j < 3; j++)
            cout << *(*(p + i) + j) << " ";
}

7. Common Mistake ❌
int *p = a;   // ❌ wrong for 2-D array

✔ Correct:

int (*p)[3] = a;

8. Pointer and 3-D Array (Concept)
int a[2][3][4];
int (*p)[3][4] = a;

Access:
*(*(*(p + i) + j) + k)

9. Key Exam Points
  • Multidimensional arrays use row-major order
  • Pointer must match column size
  • a[i][j] = *(*(a + i) + j)
  • int (*p)[n] → pointer to array of n integers
  • Important for function arguments
Pointers and Strings in C++
In C++, strings are closely related to pointers, especially when strings are handled as character arrays. Understanding this topic is important for exams, viva, and programming.

1. String as Character Array
A string in C++ can be stored as a character array terminated by '\0' (null character).

char str[] = "Hello";
Memory:

H  e  l  l  o  \0

2. Pointer to String
A pointer can point to the first character of a string.

char *p = str;

✔ p stores the address of 'H'.

3. Accessing String Using Pointer
while (*p != '\0') {
    cout << *p;
    p++;
}
Output:
Hello

4. Difference: Character Array vs Pointer String
Character Array                 Pointer String
Stored in array memory         Points to string literal
Modifiable                         Often not modifiable
Size is fixed                         Size not fixed

Example:
char s1[] = "Hello";    // ✔ modifiable
char *s2 = "Hello";    // ❌ modifying causes error

5. Passing Strings to Functions Using Pointer
void display(char *s) {
    while (*s != '\0') {
        cout << *s;
        s++;
    }
}
Call:
char name[] = "C++";
display(name);

6. Array of String Pointers
char *names[] = {"Ram", "Shyam", "Mohan"};

cout << names[1];   // Output: Shyam

7. String Functions Using Pointers
Common string functions use pointers internally:

strlen(str);
strcpy(dest, src);
strcmp(s1, s2);

8. Example Program (Exam-Oriented)
#include <iostream>
using namespace std;
int main() {
    char str[] = "Pointer";
    char *p = str;
    while (*p != '\0') 
{
        cout << *p;
        p++;
    }
    return 0;
}
Output:
Pointer

9. Important Exam Points
  • Strings are arrays of characters
  • Pointer stores address of first character
  • String ends with '\0'
  • char* is used for string handling
  • String literals should not be modified
Pointers to Pointers in C++
A pointer to a pointer is a pointer that stores the address of another pointer. In C++, this is commonly written using double asterisks (**).

1. Basic Concept
int a = 10;
int *p = &a;
int **pp = &p;

Memory relationship:

a   = 10
p   → address of a
pp  → address of p

2. Accessing Values
Expression         Meaning
a                         value of a
*p                         value at address stored in p
**pp                 value at address stored in p

cout << a << endl;      // 10
cout << *p << endl;     // 10
cout << **pp << endl;   // 10

3. Diagram (Conceptual)
pp  ──►  p  ──►  a
                                10

4. Example Program
#include <iostream>
using namespace std;
int main() {
    int x = 5;
    int *p = &x;
    int **pp = &p;

    cout << x << endl;     // 5
    cout << *p << endl;    // 5
    cout << **pp << endl;  // 5

    return 0;
}

5. Modifying Value Using Pointer to Pointer
**pp = 20;
cout << x;   // Output: 20

✔ Change reflects in the original variable.

6. Passing Pointer to Pointer to Function
Used when we need to modify the pointer itself.

Example: Dynamic Memory Allocation
#include <iostream>
using namespace std;
void allocate(int **p) {
    *p = new int;
    **p = 100;
}
int main() {
    int *ptr = NULL;
    allocate(&ptr);
    cout << *ptr;   // 100
    delete ptr;
    return 0;
}

7. Pointer to Pointer and Arrays
int a[3] = {1, 2, 3};
int *p = a;
int **pp = &p;

cout << **pp;   // Output: 1

8. Pointer to Pointer with Strings
char *name = "C++";
char **pp = &name;
cout << *name << endl;   // C
cout << **pp;            // C

9. Common Uses
  • Dynamic memory allocation
  • Handling 2-D arrays
  • Command-line arguments (char **argv)
  • Linked lists and trees
  • Function parameters that modify pointers

0 comments

Post a Comment