Pointers and Arrays
Part of the Logic & Flow section of Coddy's C++ journey — lesson 5 of 56.
Arrays and pointers have a special relationship in C++. When you declare an array, the array's name actually acts as a pointer to the first element of that array. This connection allows you to use pointers to work with arrays in powerful ways.
Consider this array declaration:
int numbers[5] = {10, 20, 30, 40, 50};
int* ptr = numbers; // ptr now points to numbers[0]Here, numbers is equivalent to &numbers[0] - both give you the address of the first element. The pointer ptr now points to the same location.
Once you have a pointer to an array, you can use pointer arithmetic to navigate through the elements. Adding 1 to a pointer moves it to the next element of the same type:
ptr++; // Now points to numbers[1]
ptr = ptr + 2; // Now points to numbers[3]You can dereference the pointer at any position to access the value: *ptr gives you the value at the current position, and *(ptr + 1) gives you the next element's value.
This pointer-array relationship enables you to iterate through arrays using pointers instead of traditional index-based loops, offering an alternative approach to array traversal.
Challenge
EasyCreate a program that uses a pointer to iterate through an array and print each element, demonstrating the relationship between pointers and arrays.
You are provided with the following array:
int values[6] = {15, 23, 8, 42, 17, 31};Your program should:
- Create a pointer named
ptrthat points to the first element of thevaluesarray - Use pointer arithmetic to iterate through all 6 elements of the array
- Print each element by dereferencing the pointer at each position
- Move the pointer to the next element using pointer arithmetic (increment the pointer)
Print each element on a separate line in the following format:
Element: [value]The output should show all 6 elements in the order they appear in the array, accessed through pointer dereferencing rather than array indexing.
Try it yourself
#include <iostream>
using namespace std;
int main() {
// Given array
int values[6] = {15, 23, 8, 42, 17, 31};
// TODO: Create a pointer named 'ptr' that points to the first element of the array
// TODO: Use a loop to iterate through all 6 elements using pointer arithmetic
// TODO: Print each element by dereferencing the pointer
// TODO: Move the pointer to the next element using pointer arithmetic
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Pointers and Memory
What is a Pointer?Address-Of OperatorDereference OperatorNull PointersPointers and ArraysDynamic Memory with 'new'Freeing Memory with 'delete'Recap - Pointer Practice2Vectors (Dynamic Arrays)
Introducing std::vectorCreating a VectorAdding ElementsAccessing ElementsVector SizeIterating with a For LoopRange-Based For LoopRemoving ElementsRecap - Vector Operations5Project: Inventory Tool
Project SetupAdding and Updating Items