Skip to content

Pointer Arrays

  • Arrays and pointers are closely related. An array name acts as a pointer to the first element of the array.
  • You can use pointers to access and manipulate array elements.
int arr[] = {10, 20, 30};
int *ptr = arr; // Pointer points to the first element of the array
cout << ptr[1]; // Outputs 20
cout << *(ptr + 2); // Outputs 30 (pointer arithmetic)
  • arr is the same as &arr[0] (address of the first element).
  • Incrementing a pointer (ptr++) moves to the next element in the array.
#include <iostream>
using namespace std;
int main() {
int arr[] = {1, 2, 3, 4, 5};
int *ptr = arr; // Pointer to first element
for(int i = 0; i < 5; i++) {
cout << "Element " << i << ": " << *(ptr + i) << endl; // Accessing array elements via pointer
}
return 0;
}

Other Examples:

int arr[10] = {23, 122, 41, 67};
cout << " address of first memory block is " << arr << endl; // 0x61fefc (sample address for arr)
cout << arr[0] << endl; // 23
cout << " address of first memory block is " << &arr[0] << endl; // 0x61fefc (same as arr)
cout << "4th " << *arr << endl; // 23
cout << "5th " << *arr + 1 << endl; // 24
cout << "6th " << *(arr + 1) << endl; // 122
cout << "7th " << *(arr) + 1 << endl; // 24
cout << "8th " << arr[2] << endl; // 41
cout << "9th " << *(arr + 2) << endl; // 41
int i = 3;
cout << i[arr] << endl; // 67 (i[arr] == *(i + arr) == arr[3])
int temp[10] = {1,2};
cout << sizeof(temp) << endl; // 40 (10 * 4 bytes)
cout << " 1st " << sizeof(*temp) << endl; // 4 (int)
cout << " 2nd " << sizeof(&temp) << endl; // 8 (pointer to int[10])
int *ptr = &temp[0];
cout << sizeof(ptr) << endl ; // 8 (pointer size)
cout << sizeof(*ptr) << endl ; // 4 (int)
cout << sizeof(&ptr) << endl ; // 8 (pointer to pointer)
int a[20] = {1,2,3,5};
cout << " ->" << &a[0] << endl; // 0x61fecc (sample address)
cout << &a << endl; // 0x61fecc (same as &a[0]; types differ but address same)
cout << a << endl; // 0x61fecc (same as above)
int *p = &a[0];
cout << p << endl; // 0x61fecc (points to first element)
cout << *p << endl; // 1 (a[0])
cout << "-> " << &p << endl; // 0x61feb0 (address of pointer variable p)
int arr[10];
// ERROR
arr = arr + 1; // Error: cannot assign to array variable (arrays are not pointers)
int *ptr = &arr[0];
cout << ptr << endl; // 0x61feac (sample address)
ptr = ptr + 1;
cout << ptr << endl; // 0x61feb0 (next int position, +4 bytes)