Feb 13, 2010 at 6:13am UTC
I get a problem when I try to compile this code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// pointer and string
#include <iostream>
using namespace std;
int main ()
{
char myStr[] = "I am a string." ;
for (int i = 0; myStr[i] != '\0' ; ++i)
cout << i[myStr];
return 0;
}
As you can see, I wrote
i[myStr], not
myStr[i]. But the result is still correct.
Can you explain me why?
Last edited on Feb 13, 2010 at 6:16am UTC
Feb 13, 2010 at 6:46am UTC
This is a weird thing C/C++ let you do. The [brackets] are just shorthand for the indirection operator.
myStr[i] is really just an alternative/simpler way to write *(myStr + i) . But to the compiler, they're the same*.
Also... *(i + myStr) is the same as *(myStr + i) because it doesn't matter which order you add the vars.... the result is the same.
Therefore...
i[myStr] works because it's the same thing as
*(i + myStr) which works because it's the same thing as
*(myStr + i) which is the same thing as
myStr[i]
But you don't really do i[myStr] ever.
* brackets are the same as indirection only as long as there's no operator overloading involved. Overloaded operators typically work very differently
Last edited on Feb 13, 2010 at 6:47am UTC