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++

Image of Wix Studio

2025: Your year to build apps that sell

Dive into hands-on resources and actionable strategies designed to help you build and sell apps on the Wix App Market.

Get started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay