常规静态分配数组如下所示,可以使用以下公式进行访问:
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,它能正常工作吗?我看不出有什么理由不这样做.