1
#include <iostream>
using namespace std;

int main()
{
    char str[]="ABCD";
    
    for(int i=0;str[i]!='\0';i++)
    {
        cout<<i[str]<<" ";
    }
    return 0;
}

The output of the following code is A B C D but i am not able to understand how we are accessing the array

Yash-patil
  • 23
  • 5
  • 3
    The language definition says that `a[b]` means `*(a + b)`. So `str[i]` and `i[str]` mean the same thing. – Pete Becker Feb 16 '23 at 03:41
  • See [With arrays, why is it the case that a[5\] == 5[a\]?](https://stackoverflow.com/questions/381542/with-arrays-why-is-it-the-case-that-a5-5a) – Jason Feb 16 '23 at 04:25

1 Answers1

0

Let's consider str has address 100 (Very simplified example).

It has 5 chars in it, so the addressed are 100, 101, 102, 103, 104, where in the 104 is '\0'

When you try to access str[i], it actually calculates the address str + i, and gets the value: *(str + i). And when you try to write the reversed way i[str], it also calculates the address i + str. So you get correct result.

Note that here is working pointer arithmetic (so for every type T you get the address pointer + sizeof(T))

And your

for(int i=0;str[i]!='\0';i++)
{
    cout<<i[str]<<" ";
}

Will access addresses 100, 101, 102, 103, 104. And print the right values.

sens
  • 71
  • 3