简体   繁体   中英

Why does an allocated 2-dimensional int array have a different sequence of memory addresses as a normal one?

The following code outputs the sequence of memory addresses of a dynamically allocated array, then a regular 2D array (of ints) via nested for loops.

#include <iostream>
using namespace std;

int main()
{
    int regArray[3][3]; //a normal 2d array
    int **allocatedArray = new int*[3];

    for (int i = 0; i < 3; i++)
        allocatedArray[i] = new int[3]; //an allocated 2d array


    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 3; j++)
            cout << &allocatedArray[i][j] << "    " << &regArray[i][j] << endl; 
            //prints the allocated array, leaves a space, then a regular one
}

The output is as follows:

0x7812e8    0x29febc
0x7812ec    0x29fec0
0x7812f0    0x29fec4
0x781300    0x29fec8
0x781304    0x29fecc
0x781308    0x29fed0
0x781318    0x29fed4
0x78131c    0x29fed8
0x781320    0x29fedc

Process returned 0 (0x0)   execution time : 0.249 s
Press any key to continue.

I know that in the regular array (right side), the next element's address results in an increase of 4 bytes (in hexadecimal form). However, in the allocated array (left side) this does not seem to be the case. During the execution of the inner for loop, there is a normal increase of 4 bytes, as expected. Whenever the outer loop iterates, there seems to be an increase of 10.

An example is when: 0x7812f0 jumps to 0x781300.

Why does this occur? Any simple explanation is appreciated.

Both of your arrays are allocated. But they use different forms of allocation ( automatic and dynamic respectively).

Your first array places 9 ints in 9 consecutive memory locations.

Your second array allocates three separate blocks of 3 consecutive memory locations. Those 3 blocks could be anywhere, they do not have to be next to each other in memory.

Your output confirms this.

The code below means to allocate a pointer to a pointer array

int **allocatedArray = new int*[3];

and here is to make each of the pointer a allocated array

allocatedArray[i] = new int[3];

The code above allocates a int array which should be 12 bytes, but between each 2 of the 1-dimensional array have no relationship.

So, the size of allocatedArray[i][j] is 4 bytes and allocatedArray[i] is 12 bytes

the 10 bytes you mentioned is just a coincidence

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