c++的一些基础的东西看不懂,一直纳闷。请帮我。 我知道 p 指向的内存是一个 3x4 大小的 2D int 矩阵。
int(*p)[3][4];
1) 为什么我不能像下面这样分配内存?
p = new int[3][4];
2) 应该像下面这样工作。但是为什么?
p = new int [1][3][4]; //or new int [5][3][4]; etc
3) 下面这行代码是什么意思?它在语义上是正确的,但它在做什么?下一行中空 [] 的意义是什么?
p = new int [ ][3][4];
最佳答案
c++ 是一种强类型语言。 int
与 int*
不同。同样,int[3]
与 int*
不是同一类型。但只要用一根棍子轻轻戳 int[3]
,它就会散开并腐烂成一个 int*
。 c++ 这样做是因为 c 这样做。
Why can't I allocate memory like following?
p = new int[3][4];
因为 new
返回一个指向 int[4]
的指针:
auto p1 = new int[3][4]; // int(*p1)[4]
数组有decayed到一个指针。它有 lost the type and first dimension .最好避免使用数组指针并坚持使用 using templates and references .或者更好的是,更喜欢 std::vector
或 std::array
。
您可以有多个指向同一地址的指针,but with different types ,这can be confusing .
2) It should be like following to work. But why?
p = new int [1][3][4];
在此示例中,int[3][4]
数组也已退化为指针:
auto p2 = new int [1][3][4]; // int(*p2)[3][4]
所以这里可以将new
返回的值赋值给p
,因为它有相同的类型。但是请注意,指针类型不包含有关数组大小的信息,它仅具有指向元素的类型,这些元素恰好是较低维度的数组(尚未退化为指针)。
3) What does following line of code mean? It is semantically correct but what is it doing? What is significance of empty [] in following line?
p = new int [ ][3][4];
这可能并不总是编译,如果编译成功,那么它是一个 compiler extension这将确定空方括号的值。
关于c++ - 使用new将内存分配给指针多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41727432/