Pointers in C++
Introduction
In modern C++, the use of pointers can be avoided in many cases.
The simplest example.
#include <iostream>
using namespace std;
/* Pointers */
int main() {
int a = 5;
int *px = &a;
int *px2 = &a;
//px is now an address in memory where variable a was stored
cout << endl << "a = " << a;
cout << endl << "pointer px: " << *px;
// will show the value stored at this address
cout << endl << "pointer px address: " << px;
// will show the address in hex format
cout << endl << "pointer px2 address: " << px2;
a = 9;
cout << endl << "a = " << a;
cout << endl << "pointer px: " << *px;
// will show the value stored at this address
cout << endl << "pointer px address: " << px;
// will show the address in hex format
cout << endl << "pointer px2 address: " << px2;
*px2 = 11;
cout << endl << "a = " << a;
cout << endl << "pointer px: " << *px;
// will show the value stored at this address
cout << endl << "pointer px address: " << px;
// will show the address in hex format
cout << endl << "pointer px2 address: " << px2;
}
g++ -std=c++23 46.cpp -o 46
./46
a = 5 pointer px: 5 pointer px address: 0x7ffe7c372fa4 pointer px2 address: 0x7ffe7c372fa4 a = 9 pointer px: 9 pointer px address: 0x7ffe7c372fa4 pointer px2 address: 0x7ffe7c372fa4 a = 11 pointer px: 11 pointer px address: 0x7ffe7c372fa4 pointer px2 address: 0x7ffe7c372fa4
#include <iostream>
using namespace std;
/* Pointers */
int main() {
const int SIZE = 5;
int arr[SIZE]{4,55,79,1,7};
for (int i = 0; i < SIZE; i++)
{
cout << arr[i] << endl;
}
// array name is a pointer to its first element
int *pArr = arr;
cout << "arr\t"<< arr << endl;
cout << "pArr\t"<< pArr << endl;
cout << "=============================" << endl;
for (int i = 0; i < SIZE; i++)
{
cout << pArr[i] << endl;
}
cout << "=============================" << endl;
// array is a continuous memory allocation
// elements are going one by one without gaps in memory
// that is why when we move pointer to the next value
// we reach to the following array element
for (int i = 0; i < SIZE; i++)
{
// by adding 1 here we are moving 4 bytes in the memory
// because we have integer values
cout << *(pArr + i) << endl;
}
cout << "=============================" << endl;
for (int i = 0; i < SIZE; i++)
{
// using pointer to go through array
cout << *(arr + i) << endl;
}
cout << "=============================" << endl;
for (int i = 0; i < SIZE; i++)
{
// here we will get the memory addresses
// note that the step is 4 bytes
cout << (arr + i) << endl;
}
}
g++ -std=c++23 47.cpp -o 47
./47
4 55 79 1 7 arr 0x7ffd3e16c400 pArr 0x7ffd3e16c400 ============================= 4 55 79 1 7 ============================= 4 55 79 1 7 ============================= 4 55 79 1 7 ============================= 0x7ffd3e16c400 0x7ffd3e16c404 0x7ffd3e16c408 0x7ffd3e16c40c 0x7ffd3e16c410
The code on this page was run with g++ 15.2.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Andrei Olegovich