#include <iostream> int main() { // Declare a pointer to int int *ptr = nullptr; // Allocate memory for an int and assign its address to the pointer ptr = new int; // Assign a value to the int pointed by the pointer *ptr = 42; // Output the value and address std::cout << "Value: " << *ptr << " at address: " << ptr << std::endl; // Deallocate the memory delete ptr; ptr = nullptr; // Allocate memory for an array of ints int size = 5; int *arr = new int[size]; // Assign values to the elements in the array for (int i = 0; i < size; i++) { arr[i] = i * 10; } // Output the values and addresses for (int i = 0; i < size; i++) { std::cout << "Value: " << arr[i] << " at address: " << &arr[i] << std::endl; } // Deallocate the memory delete[] arr; arr = nullptr; return 0; }This example demonstrates the following concepts in C++:
Pointers: Variables that store the address of another variable (e.g.,
int *ptr
). The*
operator is used to dereference the pointer and access the value it points to.Dynamic memory allocation: Using
new
anddelete
to allocate and deallocate memory. In this example, we allocate memory for a singleint
and an array ofint
s.Pointer arithmetic: In the example, we use array notation (e.g.,
arr[i]
) to access the elements of the dynamically allocated array. This is equivalent to using pointer arithmetic (*(arr + i)
).Properly deallocating memory: It’s essential to deallocate memory using
delete
for single variables ordelete[]
for arrays when they are no longer needed. We also set the pointers tonullptr
to avoid dangling pointers.