Arrays and Pointers in C++

Arrays and pointers are powerful features of C++ that allow you to work with collections of data and manipulate memory addresses directly. Understanding how to use arrays and pointers is essential for writing efficient and flexible C++ code.

Arrays

An array is a collection of elements of the same type, stored in contiguous memory locations. You can access individual elements of an array using an index, starting from zero.

Example of declaring and accessing elements of an array:

int numbers[5]; // Declaration of an integer array with 5 elements

// Initializing elements of the array
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

// Accessing elements of the array
int firstElement = numbers[0]; // firstElement = 10
int thirdElement = numbers[2]; // thirdElement = 30

In this example, we declare an integer array `numbers` with 5 elements and initialize its elements with values. We then access individual elements of the array using square brackets and indices.

Pointers

A pointer is a variable that stores the memory address of another variable. Pointers are used extensively in C++ for dynamic memory allocation, passing arguments to functions by reference, and accessing hardware directly.

Example of declaring and using pointers:

int number = 10; // Declaration of an integer variable
int *ptr; // Declaration of an integer pointer

ptr = &number; // Assigning the address of 'number' to 'ptr'

// Dereferencing 'ptr' to access the value stored at the memory address
int value = *ptr; // value = 10

In this example, we declare an integer variable `number` and an integer pointer `ptr`. We then assign the address of `number` to `ptr` using the address-of operator `&`. Finally, we dereference `ptr` to access the value stored at the memory address it points to.