Reputation: 49
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 ?
Upvotes: 0
Views: 137
Reputation: 49
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));
}
}
Upvotes: 0
Reputation: 238311
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++.
Upvotes: 1