Pointers - Comprehensive Exercise
Pointers - Comprehensive Exercise
Objective:
In this exercise, you will implement various features using pointers, arrays (as pointers), dynamic
memory allocation, and memory management. This will help you understand how pointers work,
how to manipulate arrays with pointers, and how to use dynamic memory effectively in C++.
Tasks:
1. Pointer Basics and Arithmetic:
• Declare an integer variable and a pointer to that variable.
• Use the pointer to modify the value of the variable and print both the pointer’s address and
the updated value.
• Create an array of integers and a pointer to its first element. Use pointer arithmetic to
traverse and print the elements of the array.
2. Pointer to Pointer:
• Declare an integer variable and a pointer pointing to its address.
• Create another pointer that stores the address of the first pointer (pointer to a pointer).
• Print the value of the integer through both levels of indirection.
3. Array as Pointers:
• Declare an array of integers and use a pointer to traverse and print the array elements.
Modify the values using pointer notation instead of array indexing, then print the updated
array.
4. Passing Pointers to Functions:
• Write a function that takes a pointer to an integer as a parameter and modifies the value of
the integer in the calling function. Call this function in main(), pass a pointer to an integer
variable, and print the value before and after the function call.
5. Dynamic Memory Allocation for 1D Array:
• Dynamically allocate memory for an array of integers using the new operator.
• Allow the user to input values into the array, print the array, and then release the allocated
memory using the delete[] operator.
6. Dynamic 2D Array Allocation:
• Dynamically allocate memory for a 2D array using pointers. Allow the user to define the
dimensions of the array and input values.
• Print the 2D array in matrix format and release the allocated memory once done.
7. Swapping Two Variables Using Pointers:
• Write a function to swap two integers using pointers. In main(), prompt the user to enter two
integers, call the function to swap them, and print the values after swapping.
8. Pointer and Const:
• Declare a pointer to a constant integer and a constant pointer to an integer.
• Try modifying the value of the variables in both cases and observe the compiler behavior.
Write comments in your code explaining why the behavior occurs.
#include <iostream>
int main() {
// Task 1: Pointer basics and arithmetic
int var = 20;
int *ptr = &var;
*ptr = 30;
cout << "Updated value of var: " << *ptr << endl;
// Deallocate memory
delete[] dynArr;
cout << "Before swap: a = " << a << ", b = " << b << endl;
swap(&a, &b);
cout << "After swap: a = " << a << ", b = " << b << endl;
return 0;
}