An Uncommon representation of array elements in C++ program


An array is a linear data structure that stores elements the same data type. To access a single data element of the array, there is a standard way that is commonly used.

Syntax

array_name[index];

Example

 Live Demo

#include <iostream>
using namespace std;
int main( ){
   int arr[2] = {32,65};
   printf("First Element = %d\n",arr[0]);
   printf("Second Element = %d\n",arr[1]);
   return 0;
}

Output

First Element = 32
Second Element = 65

Now, there is another method that can provide the same output as the above.

Syntax

index[array_name];

Example

 Live Demo

#include <iostream>
using namespace std;
int main( ){
   int arr[2] = {32,65};
   printf("First Element = %d\n",0[arr]);
   printf("Second Element = %d\n",1[arr]);
   return 0;
}

Output

First Element = 32
Second Element = 65

Let’s take under consideration both the cases −

arr[0] would be *(arr + 0) pointer that points to a value.

0[arr] would be *(0 + arr) pointer that points the same as the former one does.

Both the pointers point to the same memory address.

Updated on: 24-Oct-2019

64 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements