问题描述
你好
我有一个快速的问题.抱歉,这是一个新手问题,如果很明显,请原谅我.我想在C ++中有一个二维动态数组,所以我将编写如下代码:-
VERTS ** verts1; //[1]
或
VERTS *(* verts1); //[2]
我在想的是表达式[1]是一个指向指针的数组.但是什么是[2]?有人说方括号有所不同.有人可以解释这个吗?
那内存分配呢-我有以下内容:-
verts1 =新的VERTS * [num_edges];
verts1 [current_edge] =新的VERTS [num_columns];
当我解除分配时,我有:-
Hello
I have a quick question. Sorry it is a bit of a newbie question so forgive me if it is obvious. I want to have a two dimensional dynamic array in C++ so I''ll code something like this:-
VERTS** verts1; //[1]
or
VERTS*(*verts1); //[2]
What I''m thinking is that the expression [1] is an array of pointers to pointers. But what is [2]??? Someone said that the brackets make a difference. Can someone explain this???
What about memory allocation - I have the following:-
verts1 = new VERTS*[num_edges];
verts1[current_edge] = new VERTS[num_columns];
When I deallocate I have:-
if (verts1!=NULL)
{
for (int i=0; i<num_edges; i++)
delete [] verts1[i];
delete [] verts1;
}
您能验证一下此分配和解除分配吗?我很确定可以,但是如果我使用表达式VERTS *(* verts1);怎么办?这会改变什么吗?
另外,有时我想取消分配特定的行,所以有这样的内容:-
删除[] verts1 [current_edge];
这是错误的,不是吗?我不需要遍历所有这样的元素:-
Can you please verify this allocation and deallocation. I''m pretty sure it''s okay but what if I use expression VERTS*(*verts1); Does this change anything???
Also, sometimes I want to deallocate a specific row so have something like this:-
delete [] verts1[current_edge];
This is wrong isn''t it? Don''t I need to loop over all the elements like this:-
for(int i=0; i<num_columns;>{
delete verts[current_edge][i];
}
希望有人会对此有所启发,因为我有些困惑.再次抱歉,这是一个愚蠢的问题.
亲切的问候...
Hopefully, someone can throw some light on this as I''m a bit confused. Once again, sorry if this is a silly question.
Kind regards...
推荐答案
verts** verts1
是变量的声明,如果将其两次取消引用,则该变量的声明将为verts
值.因此它是指向顶点的指针"
Is a declaration of a variable that - if dereferenced twice - will result into a verts
value. So it is a "pointer to pointer to verts"
verts*(*verts1)
是创建verts*
类型的临时对象,并使用*verts1
返回的指针进行初始化.
(例如point(2,3);
这样的代码).
从概念上讲,分配和释放都很好.
但是-实际上-您实际上是在做std::vector<std::vector<vertexs> >
在后台自己做的事情.
is the creation of a temporary object of type verts*
, initialized with the pointer returned by *verts1
.
(think to code like point(2,3);
).
Allocation and deallocation are conceptually fine.
But -in fact- you''re doing exacly what std::vector<std::vector<vertexs> >
does by itself behind the scene.
std::vector<std::vector<vert> > vertices;
干杯,
灰
Cheers,
Ash
这篇关于C ++中的2D动态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!