Member-only story

C++ Pointers and Arrays: How to the store memory address using pointers

Marika Lam
2 min readMay 20, 2022

--

Storing the memory address of the first element of the array

Method 1

int *ptr;
int arr[5];

// store the address of the first
// element of arr in ptr
ptr = arr;

Here, ptr is a pointer variable while arr is an int array. The code ptr = arr; stores the address of the first element of the array in variable ptr.

Method 2

int *ptr;
int arr[5];
ptr = &arr[0];

Declaring ptr as &arr[0] is the same as arr. They will both store the same memory address, the first element of the array.

Storing the memory address of the 4th element of the array

Method 1

int *ptr;
int arr[5];
ptr = arr;

ptr + 1 is equivalent to &arr[1];
ptr + 2 is equivalent to &arr[2];
ptr + 3 is equivalent to &arr[3];
ptr + 4 is equivalent to &arr[4];

ptr+3 will point to the 4th element of the array.

Method 2

// use dereference operator
*ptr == arr[0];
*(ptr + 1) is equivalent to arr[1];
*(ptr + 2) is equivalent to arr[2];
*(ptr + 3) is equivalent to arr[3];
*(ptr + 4) is equivalent to arr[4];

The 4th element can be accessed by a single pointer like so *(ptr + 3)

--

--

No responses yet