我想我们都同意,以一维形式解引用(可能有偏移的)指向多维数组第一个元素的指针是C语言中被视为习惯用法的。例如:
void clearBottomRightElement(int *array, int M, int N)
{
array[M*N-1] = 0; // Pretend the array is one-dimensional
}
int mtx[5][3];
...
clearBottomRightElement(&mtx[0][0], 5, 3);
然而,我这个语言律师需要被说服这实际上是明确定义的C语言!特别是:
Does the standard guarantee that the compiler won't put padding in-between e.g.
mtx[0][2]
andmtx[1][0]
?Normally, indexing off the end of an array (other than one-past the end) is undefined (C99, 6.5.6/8). So the following is clearly undefined:
struct { int row[3]; // The object in question is an int[3] int other[10]; } foo; int *p = &foo.row[7]; // ERROR: A crude attempt to get &foo.other[4];
So by the same rule, one would expect the following to be undefined:
int mtx[5][3]; int (*row)[3] = &mtx[0]; // The object in question is still an int[3] int *p = &(*row)[7]; // Why is this any better?
So why should this be defined?
int mtx[5][3]; int *p = &(&mtx[0][0])[7];
那么C标准的哪一部分明确允许这样做呢?(为了讨论的方便,我们假设c99。)
编辑
请注意,我毫不怀疑这在所有编译器中都可以正常工作。我所质疑的是是否标准明确允许这样做。
[][]
访问执行的操作与*(array + x * index + y)
相同。 - RedXarr + 1 * 5 * sizeof(arrType)+ 5 * sizeof(arrType)
... - Wouter Simons