问题
I stumbled upon code containing something like:
char c = "abc"[1];
and it compiles and runs fine with gcc! c will be 'b' after this expression.
Is this standard to index literal strings or is it mere luck that it works?
回答1:
Of course it is, a string literal is of array type. It is converted to a pointer to char in the expression and is like an any pointer to char.
char c = "abc"[1];
and
char *p = "abc";
char c = p[1];
are equivalent.
回答2:
This is entirely standard. A string is actually a piece of syntactic sugar to a pointer to an array of characters, and any pointer can use subscript notation.
In fact, a[b] is equivalent to *(a + b) which in turn is equivalent to *(b + a), which leads you to the slightly surprising result that a[b] is equivalent to b[a], which is why in some code (especially, but sadly not exclusively, in obfuscated code competitions), this sort of thing:
char c = 1["abc"];
can occur.
回答3:
This is standard because a string defined by "" is converted to a char* (char pointer) which you can index. The target of that pointer is always 1 char which is b in your case.
来源:https://stackoverflow.com/questions/11503248/is-literal-string-indexing-standard-c