简体   繁体   中英

How to find out addresses of the slots in dynamically allocated multidimensional array?

I created a 2-dimensional dynamically allocated array. Then I wanted to output the addresses of the slots, so I can really see it's not a contiguous block of memory. I've managed to do that by &tda[i][j] statement. However, I'm wondering how I could do that by using something like *(tda+1) , which is the same as &tda[1][0] . For example, how could I output tda[1][1] address using a combination of *(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;
}

Well, you already mentioned the equivalence of a[k] and *(a + k) , but let me spell it out for you:

&tda[i][j]

is

&*(tda[i] + j)

is

*(tda + i) + j

Analogously,

tda[i][j]

becomes

*(*(tda + i) + j)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM