DEV Community

vultr
vultr

Posted on

Access Array Elements with Pointers in C++

Learn how to efficiently manipulate array elements using pointers in C++.

Key Concepts:
Array and Pointer Relationship:
In C++, the name of an array is essentially a pointer to its first element.

Accessing Elements Using Pointers:

Use pointer arithmetic to access array elements.
The syntax *(arr + i) fetches the element at index i.
Code Example:
cpp
Copy code

include

using namespace std;

int main() {
int arr[] = {10, 20, 30, 40, 50};
int* ptr = arr; // Pointer to the first element of the array

cout << "Accessing array elements using pointers:\n";
for (int i = 0; i < 5; i++) {
    cout << "Element " << i << ": " << *(ptr + i) << endl;
}

return 0;
Enter fullscreen mode Exit fullscreen mode

}
Explanation:
Pointer Declaration:
int* ptr = arr;

ptr now points to the first element of the array arr.
Pointer Arithmetic:

Incrementing ptr moves to the next element.
Access the value with *(ptr + i).
Output:
Displays all array elements by traversing the array via pointer arithmetic.
More Visit- Access Array Elements with Pointer C++

Top comments (0)