用C访问数组元素的不同方式 [英] Different way of accessing array elements in C
问题描述
我是一个C语言编程课程的助教,和我遇到以下行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。我发现了这片code在一套技术面试问题。有谁知道为什么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.
您的帮助将大大AP preciated!
Your help will be greatly appreciated!
推荐答案
完全有效C.从维基百科:
类似地,由于前pression一个[i]为语义上等同于*(A + I),这又相当于*第(i + a)中,前pression也可以写成作为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屋!