Pointer Notation in C++
In C++, a pointer is an object that is used to store the memory address of another object which allows the pointer to access the data stored in another object and manipulate it. Pointers are mainly used for dynamic memory allocation and deallocation.
- Now, if we allocate multiple element block using new to this pointer, we can use it arrays with the index pointing to the (n-1)th element in the block.
- We can also use the pointer as array if we assign the address of the first element of an array to the pointer.
Syntax of Pointer to Array in C++
dataType *ptrName = &anyArray[0];
or
dataType *ptrName = new int[size]
Here, the pointer is indicated by an asterisk(*) before the ptrName.
- dataType is the data type of the variable the pointer is pointing to.
- ptrName is the name of the pointer.
- anyArray is the name of some array.
- size is the size of the array.
Example
The below example demonstrates the use of pointer to access a value of a variable in C++.
// C++ program to demonstrate the usage of pointer
#include <iostream>
using namespace std;
// utility function to print array
void printArr(int* arr, int size)
{
for (int i = 0; i < size; i++) {
// Access and print array elements using the pointer
cout << arr[i] << " ";
}
cout << endl;
}
// driver code
int main()
{
// size of the array
int size = 5;
// Define and initialize an array
int arr[] = { 10, 22, 30, 44, 50 };
// Pointer to the first element of the array
int* ptr = arr;
int* ptr2 = new int[size];
for (int i = 0; i < size; i++) {
ptr2[i] = i + 1;
}
cout << "Elements of Static Array: ";
printArr(ptr, size);
cout << "Elements of Dynamic Array: ";
printArr(ptr2, size);
return 0;
}
Output
Elements of Static Array: 10 22 30 44 50 Elements of Dynamic Array: 1 2 3 4 5
To learn more about pointers in C++ refer: C++ Pointers
Difference Between Pointers and Array Notations in C++
In C++, pointers and array notations are two ways using which we work with arrays and memory for accessing the data. They have distinct behaviours and are used in different contexts. In this article, we will learn the key differences between pointers and array notations in C++.