如何在动态分配的多维数组中找出插槽的地址?

时间:2015-05-25 19:39:19

标签: c++ arrays multidimensional-array

我创建了一个二维动态分配的数组。然后我想输出插槽的地址,所以我真的可以看到它不是一块连续的内存块。我已经设法通过&tda[i][j]声明做到了这一点。但是,我想知道如何使用类似*(tda+1)的内容来实现这一点,这与&tda[1][0]相同。例如,如何使用tda[1][1]

的组合输出*(tda+1)地址
#include <iostream>
using namespace std;

int main() {
   int **tda;
   tda = new int*[2];

   cout << tda << endl;
   cout << tda+1 << endl;

   for (int i=0; i<2; i++) {
       tda[i] = new int[2];
   }

   cout << *(tda+1) << endl;

   cout << endl << "Proof that the block of memory is not contiguous:" << endl;
   for (int i=0; i<2; i++) {
       for (int j=0; j<2; j++) {
            cout << &tda[i][j] << endl;
        }
    }


    return 0;
}

1 个答案:

答案 0 :(得分:2)

嗯,你已经提到了a[k]*(a + k)的等价,但让我为你拼出来:

&tda[i][j]

&*(tda[i] + j)

*(tda + i) + j

类似地,

tda[i][j]

变为

*(*(tda + i) + j)