常规的静态分配数组看起来像这样,可以使用以下公式进行访问:
const int N = 3;
const int M = 3;
int a1[N][M] = { {0,1,2}, {3,4,5}, {6,7,8} };
int x = a1[1][2]; // x = 5
int y = *(a1+2+N*1); // y = 5, this is what [] operator is doing in the background
数组是内存的连续区域。在动态数组分配的情况下,它的外观有所不同,变成了指向数组的指针数组:
int** a2 = new int*[N];
for (int i = 0; i < N; i++)
a2[i] = new int[M];
//Assignment of values as in previous example
int x = a2[1][2];
int y = *(*(a2+1))+2); // This is what [] operator is doing in the background, it needs to dereference pointers twice
从我们可以看到,使用[]操作符进行操作在典型连续数组和动态分配数组中完全不同。
- 我对[]操作的理解是否正确?
- C/C++编译器如何区分应执行哪个[]操作,并在哪里实现它?我能够想象通过重载C++中的[]运算符来自己实现它,但是C/C++是如何处理它的?
- 在C语言中使用malloc而不是new会正常工作吗?实际上我没有看到任何不行的理由。