← Back to C++ Course | Chapter 7: Pointers & References | Lesson 5 of 11

C++ Pointers & Arrays

Array Name as Pointer

In C++, the name of an array acts as a constant pointer to its first element, so you can assign the array name directly to a pointer variable without using the address-of operator. This is why functions that accept arrays are actually receiving a pointer, not a copy of the whole block.

Example: Array Name as Pointer

cpp
#include <iostream>

int main() {
	int arr[] = {1, 2, 3};
	int *ptr = arr; // array name decays to a pointer to its first element
	std::cout << *ptr << std::endl;
	return 0;
}

Pointer Arithmetic

You can use pointer arithmetic to navigate through an array: incrementing a pointer with ptr++ moves it forward by exactly sizeof(type) bytes, not one byte, so the compiler automatically scales the jump to the element type. This lets you walk a buffer without ever writing an index variable.

Example: Pointer Arithmetic

cpp
#include <iostream>

int main() {
	int arr[] = {1, 2, 3};
	int *ptr = arr;
	ptr++;
	std::cout << *ptr << std::endl;
	return 0;
}

Accessing Array Elements with Pointers

Instead of using brackets like arr[i], you can use dereferenced pointer offsets like *(ptr + i) to read or modify any element in an array, and in fact arr[i] is defined by the language as shorthand for exactly that expression. Knowing this equivalence explains a lot of pointer-heavy legacy C++ code.

Example: Accessing Array Elements with Pointers

cpp
#include <iostream>

int main() {
	int arr[] = {10, 20, 30};
	int *ptr = arr;
	std::cout << *(ptr + 1) << std::endl;
	return 0;
}

Dynamically Allocated Arrays

You can allocate dynamic arrays on the heap using the 'new[]' operator, which lets you set the array size at runtime instead of at compile time. Remember to release this memory using 'delete[]' when finished, since forgetting the brackets or the call entirely leaks memory silently.

Example: Dynamically Allocated Arrays

cpp
#include <iostream>

int main() {
	int size = 3;
	int *arr = new int[size];
	arr[0] = 1;
	arr[1] = 2;
	arr[2] = 3;
	std::cout << arr[1] << std::endl;
	delete[] arr;
	return 0;
}

Passing Arrays to Functions using Pointers

When you pass an array to a function, it decays into a pointer to its first element rather than being copied, which is efficient but also means the function loses the array's size information. That's why array-processing functions usually take an explicit length parameter alongside the pointer.

Example: Passing Arrays to Functions using Pointers

cpp
#include <iostream>

void printFirst(int *arr) {
	std::cout << arr[0] << std::endl;
}

int main() {
	int nums[] = {5, 10, 15};
	printFirst(nums);
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.