错误的数组索引不会导致错误
Wrong array indexing does not cause error
考虑以下程序:
#include <stdio.h>
int main(void)
{
int a[] = {1, 2, 3};
for (size_t i = 0; i < 3; i++)
printf ("%i\n", a[0, i]);
return 0;
}
显然,一维数组 a
的访问方式与 Python 中的二维数组一样。但是,此代码编译时会出现 unused-value
警告。我预计它会产生一个错误,因为我一直认为这个 for is of multiindexing 在 C 中是完全错误的(参见 K&R 第 112 页)。令我惊讶的是,上面的代码确实打印出了数组元素。
如果将第六行的 a[0, i]
更改为 a[i, 0]
,第一个数组元素将打印三次。如果你使用 a[i, 1]
第二个元素被打印三次。
一维数组上语法错误的多索引如何转换为指针算术以及 a[i, 0]
结果的什么值未使用?
而且,是的,我知道如何在 C 中使用多索引。
0, i
是 C 中的有效表达式。逗号是计算两个操作数并丢弃左侧操作数结果的运算符。在a[0, i]
中使用时,相当于a[i]
。而 a[i, 0]
等同于 a[0]
.
(请注意,在 f(a, b, c)
等函数调用中,逗号是参数分隔符。这是 C 语法的不同部分,在此上下文中逗号不是运算符。)
这里的逗号,就是comma operator。它不是多索引(理想情况下应该是 [0][i]
或 [i][0]
的形式)。
引用 C11
,章节 §6.5.17(强调我的)
The left operand of a comma operator is evaluated as a void expression; there is a
sequence point between its evaluation and that of the right operand. Then the right
operand is evaluated; the result has its type and value.
所以,在你的情况下,
a[0, i]
与
相同
a[i]
和
a[i, 0]
与
相同
a[0]
考虑以下程序:
#include <stdio.h>
int main(void)
{
int a[] = {1, 2, 3};
for (size_t i = 0; i < 3; i++)
printf ("%i\n", a[0, i]);
return 0;
}
显然,一维数组 a
的访问方式与 Python 中的二维数组一样。但是,此代码编译时会出现 unused-value
警告。我预计它会产生一个错误,因为我一直认为这个 for is of multiindexing 在 C 中是完全错误的(参见 K&R 第 112 页)。令我惊讶的是,上面的代码确实打印出了数组元素。
如果将第六行的 a[0, i]
更改为 a[i, 0]
,第一个数组元素将打印三次。如果你使用 a[i, 1]
第二个元素被打印三次。
一维数组上语法错误的多索引如何转换为指针算术以及 a[i, 0]
结果的什么值未使用?
而且,是的,我知道如何在 C 中使用多索引。
0, i
是 C 中的有效表达式。逗号是计算两个操作数并丢弃左侧操作数结果的运算符。在a[0, i]
中使用时,相当于a[i]
。而 a[i, 0]
等同于 a[0]
.
(请注意,在 f(a, b, c)
等函数调用中,逗号是参数分隔符。这是 C 语法的不同部分,在此上下文中逗号不是运算符。)
这里的逗号,就是comma operator。它不是多索引(理想情况下应该是 [0][i]
或 [i][0]
的形式)。
引用 C11
,章节 §6.5.17(强调我的)
The left operand of a comma operator is evaluated as a void expression; there is a sequence point between its evaluation and that of the right operand. Then the right operand is evaluated; the result has its type and value.
所以,在你的情况下,
a[0, i]
与
相同a[i]
和
a[i, 0]
与
相同a[0]