Pointers and Arrays in C++
In C++, arrays and pointers are closely related. The name of an array acts as a pointer to its first element. This allows pointers to access array elements using pointer arithmetic, making arrays and pointers interchangeable in many situations.
Key Points
- The name of an array (e.g.,
arr) is a pointer to its first element. - You can use pointers to traverse arrays using arithmetic operations like
+,-,++, and--. - Access array elements using either
arr[index]or*(ptr + index).
Example: Array Traversal Using Pointer
#include <iostream>
using namespace std;
int main() {
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr; // Pointer to the first element of the array
cout << "Accessing array elements using pointer:" << endl;
for(int i = 0; i < 5; i++) {
cout << "Element " << i << ": " << *(ptr + i) << endl;
}
return 0;
}
Output
Element 0: 10 Element 1: 20 Element 2: 30 Element 3: 40 Element 4: 50
Example: Modifying Array Elements Using Pointer
#include <iostream>
using namespace std;
int main() {
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr;
// Modify elements using pointer
for(int i = 0; i < 5; i++) {
*(ptr + i) += 5;
}
cout << "Array after modification: ";
for(int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
Output
Array after modification: 15 25 35 45 55
Important Notes
- Pointers and arrays can be used interchangeably for accessing and modifying elements.
- Pointer arithmetic automatically accounts for the size of the data type when incrementing or decrementing.
- Be careful not to access memory outside the bounds of the array to prevent undefined behavior.
Next Topic
Next, learn about C++ References.