为什么只有第二个数组维度很重要?
为什么在处理二维数组时只有第二维对编译器很重要?我就是无法理解这一点。 谢谢
Why when working with two dimensional arrays only second dimension is important for a compiler? Just can't get my head around that.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为编译器需要弄清楚如何从内存中访问数据。第一个维度并不重要,因为当给定所有其他大小时,编译器可以计算项目的数量。
示例:
编译器知道为 4 个整数分配空间。现在,这样:
编译器无法决定它应该是a2[1][6]还是a2[2][3]还是a2[3][2]还是a2[6][1]。一旦你告诉它第二个维度,它就可以计算第一个维度。
例如,尝试访问元素 a2[1][0] 将根据声明产生不同的值。您可能会获得 2、3、4 甚至无效的位置。
Because compiler needs to figure out how to access the data from memory. The first dimension is not important because compiler can count the number of items when all other sizes are given.
Examples:
compiler knows to allocate space for 4 integers. Now, with this:
compiler cannot decide whether it should be a2[1][6] or a2[2][3] or a2[3][2] or a2[6][1]. Once you tell it the second dimension, it can calculate the first one.
For example, trying to access element a2[1][0] would yield different values depending on the declaration. You could get 2, 3, 4 or even invalid position.
它不是“第二个维度”(除非你只有两个维度)——它是“除了第一个维度之外的所有维度”。例如,您可以使用
int a[][2][3][4]
。如果没有这些维度,就不可能计算元素的地址。It's not the "second dimension" (except when you only have 2 dimensions) - it's "all but the first dimension". So you can have
int a[][2][3][4]
for example. Without these dimensions it would not be possible to calculate the address of an element.坐下来思考如何在给定数组的起始位置的情况下找到 a[i][j] 的内存位置。
请注意,c 数组的布局如下
a[0][0]
a[0][1]
a[0][2]
> ...a[0][M]
a[1][0]
...旁注: FORTRAN 数组的布局不同的是:
a[1][1]
a[2][1]
a[3][1]
...a[N][1]
a[1][2]
...注意这将如何改变查找内存位置所需的维度。
Sit down and figure out how to find the memory position of
a[i][j]
given the starting position of the array.Note that c arrays are laid out like this
a[0][0]
a[0][1]
a[0][2]
...a[0][M]
a[1][0]
...Side note: FORTRAN arrays are laid out differently:
a[1][1]
a[2][1]
a[3][1]
...a[N][1]
a[1][2]
...Notice how this would change which dimension is needed for finding memory positions.