Supposing we have a 2-d array a[n][m]
. Instead of a[i][j]
I can use *(*a + i * n + j)
.
假设我们有一个二维数组a [n] [m]。而不是[i] [j]我可以使用*(* a + i * n + j)。
How can I access an element of N-dimensional array using pointers? i.e What can I use instead of a[i][j]...[k]
?
如何使用指针访问N维数组的元素?即我可以使用什么而不是[i] [j] ...... [k]?
For example, I tried doing the following, but this doesn't work:
例如,我尝试执行以下操作,但这不起作用:
#include<iostream>
#include<conio.h>
using namespace std;
int main() {
const int n1 = 5, n2 = 5, n3 = 5;
int array[n1][n2][n3];
for (int i = 0; i < n1; i++)
for (int j = 0; j < n2; j++)
for (int k = 0; k < n3; k++)
array[i][j][k] = n1*n2*n3;
cout << array[1][2][4]<<endl;
cout << *(*array + n1 + n2 * 2 + 4);
_getch();
return 0;
}
1 个解决方案
#1
1
Quote from N1256 6.5.2.1 Array subscripting
引自N1256 6.5.2.1数组下标
The definition of the subscript operator [] is that
E1[E2]
is identical to(*((E1)+(E2)))
.下标运算符[]的定义是E1 [E2]与(*((E1)+(E2)))相同。
From this, I can say that all of the followings are equivalent:
由此可以说,以下所有内容都是等效的:
a[i][j][k]
(*(a + i))[j][k]
(*((*(a + i)) + j))[k]
(*((*((*(a + i)) + j)) + k))
Note: The added code is C++, not C. For C++, N3337 5.2.1 Subscripting says that:
注意:添加的代码是C ++,而不是C.对于C ++,N3337 5.2.1 Subscripting说:
The expression
E1[E2]
is identical (by definition) to*((E1)+(E2))
表达式E1 [E2]与*((E1)+(E2))相同(根据定义)
#1
1
Quote from N1256 6.5.2.1 Array subscripting
引自N1256 6.5.2.1数组下标
The definition of the subscript operator [] is that
E1[E2]
is identical to(*((E1)+(E2)))
.下标运算符[]的定义是E1 [E2]与(*((E1)+(E2)))相同。
From this, I can say that all of the followings are equivalent:
由此可以说,以下所有内容都是等效的:
a[i][j][k]
(*(a + i))[j][k]
(*((*(a + i)) + j))[k]
(*((*((*(a + i)) + j)) + k))
Note: The added code is C++, not C. For C++, N3337 5.2.1 Subscripting says that:
注意:添加的代码是C ++,而不是C.对于C ++,N3337 5.2.1 Subscripting说:
The expression
E1[E2]
is identical (by definition) to*((E1)+(E2))
表达式E1 [E2]与*((E1)+(E2))相同(根据定义)