简体   繁体   中英

C++ 2D pointer array

I am confused how to allocate "2D array" of pointers.

With some experimenting I have managed to allocate something, which seems to be working, but I have no idea why, so explanation would be great.

This is my whole code:

#include <iostream>


using namespace std;


int main() {


int *** ptr = (int ***)malloc(sizeof(int)* 100*100);
for (int i = 0; i < 100; ++i)
{
    ptr[i] = (int**)malloc(sizeof(int) * 100);
    for (int j = 0; j < 100; ++j)
        ptr[i][j] = (int*)malloc(sizeof(int) * 100);
}


cout << *ptr[20][20] << endl;
cout << *ptr[99][20] << endl;


}

Ok, they are printing out "garbage values" but it seems good unlike other things I have tried.
So if I am not misteaken this should be equivalent to array[100][100].

My questin is why does each "level" of pointer must have size.

in this line:

for (int j = 0; j < 100; ++j)
        ptr[i][j] = (int*)malloc(sizeof(int) * 100);
}

it looks to me like we are making that each coordinate of 2d array ( I am aware that this is not as same as 2d array ) can hold size of 100 integers, and I only want to save one integer.

but If I remove it like this

for (int j = 0; j < 100; ++j)
        ptr[i][j] = (int*)malloc(sizeof(int));
}

Then my program stops working. Why ?

 ptr[i] = (int**)malloc(sizeof(int) * 100); 

ptr[i] points to a memory block that has room for 100 int objects. However, your program tries to cram 100 int** objects into that memory block. If sizeof(int**) > sizeof(int) and it probably is, then you overflow the allocated memory. The behaviour is undefined.

sizeof(int)* 100*100 on the other hand is probably way more than is needed for 100 int*** objects.


C++ introduced a feature called new expressions, which implicitly calculate for you the memory required for the allocated object or an array of objects. Use them to avoid bugs like this. They have (almost) made malloc obsolete in C++.

I have accepted using vectors is best solution for my problem, but just in case someone needs this in future, this is what I wanted to do:

int *** p2 = (int ***)malloc(sizeof(int **)* 100);
for (int i = 0; i < 100; i++)
p2[i] = (int **)malloc(sizeof(int *)* 100);


for (int i = 0; i < 100; i++) {
    for (int j = 0; j < 100; j++) {
        p2[i][j] = (int *)malloc(sizeof(int));

    }
}

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