C++ Online Compiler
Example: Pointer to First Element Access in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Pointer to First Element Access #include <iostream> using namespace std; int main() { // Step 1: Declare and initialize an integer array int numbers[] = {10, 20, 30, 40, 50}; int size = sizeof(numbers) / sizeof(numbers[0]); // Step 2: Declare an integer pointer and make it point to the first element of the array // The name of an array (without brackets) decays to a pointer to its first element. int* ptr = numbers; // Alternatively, you could use: int* ptr = &numbers[0]; // Step 3: Access elements using pointer arithmetic (ptr + index) and dereference cout << "Accessing elements using a pointer to the first element (offset method):" << endl; for (int i = 0; i < size; ++i) { cout << "Element at index " << i << ": " << *(ptr + i) << endl; } return 0; }
Output
Clear
ADVERTISEMENTS