Understanding and Analyzing Pointer Manipulation in C++ — Part 2

ANSIF
2 min readApr 22, 2024

--

#include <iostream>
#include <stdexcept> // for std::out_of_range
#include <algorithm> // for std::sort
using namespace std;

int main()
{
const int size = 10; // Size of the array
int* arr = new int[size]; // Dynamic memory allocation

// Seed for random number generation
srand(time(nullptr));

// Inserting random values into the array
cout << "Random values inserted into the array: ";
for (int i = 0; i < size; ++i) {
arr[i] = rand() % 100; // Generate random number between 0 and 99
cout << arr[i] << " ";
}

// Sorting the array
cout << endl<< "Sorting the array..." << endl;
std::sort(arr, arr + size);

// Printing the sorted array
cout << "Sorted array: ";
for(int i = 0; i < size; ++i) {
cout << arr[i] << " ";
}
cout << endl;

// Pointer operations
int* p = arr;
cout << "Pointer operations:" << endl;
cout << "First element: " << *p << endl; // First element of sorted array
cout << "Last element: " << *(p + size - 1) << endl; // Last element of sorted array

// Moving the pointer forward and accessing elements
p = p+5;

// Using try-catch for handling out-of-range access
try {
cout << "Accessing element after moving pointer forward to 5th address: " << *p << endl; // May throw exception
} catch (const std::out_of_range& e) {
cout << "Exception caught: " << e.what() << endl; // Print exception message
}

// Deallocate memory
delete[] arr;

return 0;
}

Example Output

Random values inserted into the array: 86 58 99 87 27 54 65 40 69 60 
Sorting the array...
Sorted array: 27 40 54 58 60 65 69 86 87 99
Pointer operations:
First element: 27
Last element: 99
Accessing element after moving pointer forward to 5th address: 65

Code Explanation

  1. srand(time(nullptr)): Seeds the random number generator with the current time, ensuring different sequences of random numbers on each program execution.
  2. rand() % 100: Generates a random number between 0 and 99 and inserts it into the array.
  3. std::sort(arr, arr + size): Sorts the array in ascending order using the std::sort algorithm from the <algorithm> header.
  4. Pointer operations: Demonstrates basic pointer operations like accessing elements and moving the pointer forward.
  5. Exception handling: Uses a try-catch block to handle potential out-of-range access when moving the pointer forward.
  6. Memory deallocation: Deletes the dynamically allocated memory to prevent memory leaks.

--

--

ANSIF
ANSIF

No responses yet