C中访问数组元素的不同方式 [英] Different way of accessing array elements in C
问题描述
我是 C 编程课程的助教,我遇到了以下 C 代码行:
I am a teaching assistant for a C programming course, and I came across the following line of C code:
char str[] = "My cat's name is Wiggles.";
printf("%c %c %c %c\n", str[5], *(str + 5), *(5 + str), 5[str]);
我之前从未遇到过最后一个参数 (5[str]
),我的教授也没有遇到过.我认为 K&R 和 C Primer Plus 中没有提到它.我在一组技术面试问题中找到了这段代码.有谁知道为什么 C 也允许您以这种方式访问数组元素?我从来没有听说过括号外的索引和括号内的数组名.
I never came across the very last argument (5[str]
) before, and neither did my professor. I don't think it's mentioned in K&R and C Primer Plus. I found this piece of code in a set of technical interview questions. Does anyone know why C allows you to access an array element that way also? I never heard of an index being outside the set of brackets and the name of an array inside the brackets.
非常感谢您的帮助!
推荐答案
完全有效的 C.来自 维基百科:
Perfectly valid C. From Wikipedia:
同样,由于表达式 a[i] 在语义上等价于 *(a+i),而后者又等价于 *(i+a),因此该表达式也可以写成 i[a](虽然这表格很少使用).
Similarly, since the expression a[i] is semantically equivalent to *(a+i), which in turn is equivalent to *(i+a), the expression can also be written as i[a] (although this form is rarely used).
古怪,但有效.
这篇关于C中访问数组元素的不同方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!