符号 i[array] 在 C 中如何工作?
How does the notation i[array] work in C?
我在任何其他编程语言中都没有遇到过类似的表示法,即我习惯于在括号内看到下标(而不是相反)。我理解如何给定一个数组 foo
,foo
本质上是一个指向数组基址的指针;以及指针符号如何与数组符号相关联,即我明白为什么 foo[i], *(foo + i), *(i + foo)
都是等价的背后的基本原理......但我不明白 i[foo]
也等价于上述三个的背后的基本原理,或者它是如何工作的。也许用英语改写这个符号会有帮助,但我不知道该怎么做。
根据 C 标准(6.5.2.1 数组下标)
2 A postfix expression followed by an expression in square brackets []
is a subscripted designation of an element of an array object. The
definition of the subscript operator [] is that E1[E2] is identical to
(*((E1)+(E2))). Because of the conversion rules that apply to the
binary + operator, if E1 is an array object (equivalently, a pointer
to the initial element of an array object) and E2 is an integer,
E1[E2] designates the E2-th element of E1 (counting from zero).
所以由于操作的可交换性 + 你可以写
a[i]
两者兼而有之
*( a + i )
或喜欢
i[a]
让我们考虑以下 multi-dimensional 数组的声明
char * a[][2] =
{
{ { "Hello" }, { "World" } },
{ { "Hi" }, { "everybody" } }
};
要访问字符串文字“everybody”的字母 'v',您可以编写 en 表达式
a[1][1][1]
这样计算的
*( *( *( a + 1 ) + 1 ) + 1 )
表达式可以改写成
*( 1 + *( 1 + *( 1 + a ) ) )
反过来可以重写为
1[1[1[a]]]
这是一个演示程序
#include <stdio.h>
int main( void )
{
char *a[][2] =
{
{ { "Hello" }, { "World" } },
{ { "Hi" }, { "everybody" } }
};
printf( "%c\t%c\n", a[1][1][1], *( *( *( a + 1 ) + 1 ) + 1 ) );
printf( "%c\t%c\n", *( 1 + *( 1 + *( 1 + a ) ) ), 1[1[1[a]]] );
}
它的输出是
v v
v v
我在任何其他编程语言中都没有遇到过类似的表示法,即我习惯于在括号内看到下标(而不是相反)。我理解如何给定一个数组 foo
,foo
本质上是一个指向数组基址的指针;以及指针符号如何与数组符号相关联,即我明白为什么 foo[i], *(foo + i), *(i + foo)
都是等价的背后的基本原理......但我不明白 i[foo]
也等价于上述三个的背后的基本原理,或者它是如何工作的。也许用英语改写这个符号会有帮助,但我不知道该怎么做。
根据 C 标准(6.5.2.1 数组下标)
2 A postfix expression followed by an expression in square brackets [] is a subscripted designation of an element of an array object. The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))). Because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).
所以由于操作的可交换性 + 你可以写
a[i]
两者兼而有之
*( a + i )
或喜欢
i[a]
让我们考虑以下 multi-dimensional 数组的声明
char * a[][2] =
{
{ { "Hello" }, { "World" } },
{ { "Hi" }, { "everybody" } }
};
要访问字符串文字“everybody”的字母 'v',您可以编写 en 表达式
a[1][1][1]
这样计算的
*( *( *( a + 1 ) + 1 ) + 1 )
表达式可以改写成
*( 1 + *( 1 + *( 1 + a ) ) )
反过来可以重写为
1[1[1[a]]]
这是一个演示程序
#include <stdio.h>
int main( void )
{
char *a[][2] =
{
{ { "Hello" }, { "World" } },
{ { "Hi" }, { "everybody" } }
};
printf( "%c\t%c\n", a[1][1][1], *( *( *( a + 1 ) + 1 ) + 1 ) );
printf( "%c\t%c\n", *( 1 + *( 1 + *( 1 + a ) ) ), 1[1[1[a]]] );
}
它的输出是
v v
v v