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.
Char pointers point to the memory location at the start of a string, and the array indexes (eg,
str[i]) are basically addingiiterations to the start of the string.So,
str + i=str[i]=i[str]=i + strUsing this inside
printf, like you are doing, all of these will evaluate the same:See also: With arrays, why is it the case that a[5] == 5[a]?