Is literal string indexing standard C?

若如初见. 提交于 2019-12-22 10:59:45

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!