分配二维字符数组
构造函数
这就是我分配它的方式:
char **board = new char*[width];
for(i = 0; i < width; i++){
board[i] = new char[height];
for(j = 0; j < height; j++)
board[i][j] = 0;
}
this->board = &board;
在类内部,它是:
char ***board;
析构函数:
现在我想删除它,所以我写了这个(将它放在类字段中):
for(i = 0; i < width; i++)
delete (*board)[i];
delete (*board);
运行这个时:
Board* b = new Board(16, 30, 99);
delete b;
我收到一个未处理的异常。为什么?
Constructor
This is how I'm allocating it:
char **board = new char*[width];
for(i = 0; i < width; i++){
board[i] = new char[height];
for(j = 0; j < height; j++)
board[i][j] = 0;
}
this->board = &board;
Inside the class, it's:
char ***board;
Destructor:
Now I want to delete it, so I wrote this (the board it the class field):
for(i = 0; i < width; i++)
delete (*board)[i];
delete (*board);
When running this:
Board* b = new Board(16, 30, 99);
delete b;
I get an Unhandled exception. Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在堆栈上存储指向变量的指针,一旦构造函数返回,该指针就会变得无效。您应该将类的数据成员声明为
char **board
并分配this->board = board
。编辑:另请参阅@Kerrek SB 的评论。局部变量是多余的。只需直接使用数据成员(不带
this->
)。编辑2:矩形数组最好创建为单个数组,使用指针算术进行索引(无论如何,编译器对声明的二维数组都是这样做的):
这样做的优点是只需要一次内存分配(因此需要一个
delete[]
)。它还提高了缓存局部性,因为单元是连续的。更好的是,如果您在编译时知道尺寸,请使用模板:
这根本不需要内存分配(当然,除了
新板
)。You are storing a pointer to a variable on the stack, which becomes invalid as soon as the constructor returns. You should declare your class's data member as
char **board
and assignthis->board = board
.EDIT: See also @Kerrek SB's comment. The local variable is redundant. Just use the data member directly (without the
this->
).EDIT 2: Rectangular arrays are best created as a single array, using pointer arithmetic to index (which is what the compiler does with declared 2D arrays anyway):
This has the advantage of requiring just one memory allocation (and therefore one
delete[]
). It also improves cache locality because the cells are contiguous.Even better, if you know the dimensions at compile-time, use templates:
This requires no memory allocation at all (other than the
new Board
, of course).任何您
新增
的内容都需要以完全相同的方式删除
:在这种情况下不需要取消引用。
Anything that you
new
you need todelete
, in the exact same way:No dereferencing is needed in this case.
您应该使用 C++ 的强大功能。
您现在所要做的就是
board[y].push_back(char_x_val)
以便将新元素附加到末尾。您可以像任何其他二维数组一样对待board[y][x]
(好吧,几乎),但不用担心释放。在此处了解有关向量的更多信息。 (有人知道一个好的教程吗?)
You should use the powers of C++.
All you've got to do now is
board[y].push_back(char_x_val)
in order to append a new element to the end. You can treatboard[y][x]
just like any other 2D array (well, almost), but not worry about the deallocation.Read up more on vectors here. (Anyone know a good tutorial?)