[英]C++ 2D pointer array
I am confused how to allocate "2D array" of pointers. 我很困惑如何分配指针的“ 2D数组”。
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]. 因此,如果我没有误解,那么它应该等效于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. 在我看来,我们正在使2d数组的每个坐标(我知道这与2d array不同)可以容纳100个整数,而我只想保存一个整数。
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. ptr[i]
指向一个可以容纳100个int
对象的存储块。 However, your program tries to cram 100 int**
objects into that memory block. 但是,您的程序尝试将100个
int**
对象填充到该内存块中。 If sizeof(int**) > sizeof(int)
and it probably is, then you overflow the allocated memory. 如果
sizeof(int**) > sizeof(int)
可能是,则溢出分配的内存。 The behaviour is undefined. 该行为是不确定的。
sizeof(int)* 100*100
on the other hand is probably way more than is needed for 100 int***
objects. 另一方面,
sizeof(int)* 100*100
可能比100个int***
对象所需要的更多。
C++ introduced a feature called new expressions, which implicitly calculate for you the memory required for the allocated object or an array of objects. C ++引入了一项称为新表达式的功能,该功能为您隐式计算分配的对象或对象数组所需的内存。 Use them to avoid bugs like this.
使用它们来避免此类错误。 They have (almost) made
malloc
obsolete in C++. 他们(几乎)使
malloc
在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));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.