1

Possible Duplicate:
In C arrays why is this true? a[5] == 5[a]

In a C++ reference book, I found an example that accessed a string like following:

void main()
{
    char *str = "Test";
    int len, i;

    clrscr();

    len = strlen(str);
    for(i=0 ; i<len ; i++)
    {
        printf("%c", i[str]);
    }

    getch();
}

Why does i[str] work? i is a variable, not an array.

It also works if the string is declared as str[] instead of *str.

Community
  • 1
  • 1
excitive
  • 123
  • 1
  • 2
  • 11

3 Answers3

0

It works because in C i[str] and str[i] are equivalent

shf301
  • 31,086
  • 2
  • 52
  • 86
0

i[str] and str[i] evaluate the same way (as *(str+i) )

When you declare str[], str is a pointer to the first element of the array

Osiris
  • 4,195
  • 2
  • 22
  • 52
  • Okay to generalize it, we can say that constant[pointer] and pointer[constant] are same? Because liberal understanding would say that str means some hex value of a memory address, which will mean i[str] is actually constant[0x123213] ... ??? – excitive Dec 07 '12 at 05:47
0

Char pointers point to the memory location at the start of a string, and the array indexes (eg, str[i]) are basically adding i iterations to the start of the string.

So, str + i = str[i] = i[str] = i + str

Using this inside printf, like you are doing, all of these will evaluate the same:

printf("%c", str[i]);
printf("%c", i[str]);
printf("%c", *(str+i));
printf("%c", *(i+str));

See also: With arrays, why is it the case that a[5] == 5[a]?

Community
  • 1
  • 1
cegfault
  • 6,442
  • 3
  • 27
  • 49
  • Great, this explains it. So as I understand it, since the compiler knows that out of i and str, str is the pointer. So the memory area str points to are supposed to be accessed and not of i, even if we write i outside the brackets? – excitive Dec 07 '12 at 05:52
  • yes. the compiler is essentially adding the two numbers, and either way you add them you get to the same place – cegfault Dec 07 '12 at 05:54