二维阵列的动态分配
Dynamical allocation of 2D-array
有人可以告诉我这个代码片段的描述吗?
chessBoard = new char*[ tRows ] ;
for ( unsigned int c = 0; c < rows; c++ )
{
chessBoard[ c ] = new char[ columns ];
}
问题:
什么是char*[tRows]
,它的效果是什么?
而且,什么是chessBoard[c]
?
请给我准确的描述。
char *chessBoard = new char[ tRows ] ; //correct definition
//chessBoard is a pointer to array of tRow size of characters
for( unsigned int c = 0 ; c < rows ; c++ )
chessBoard[ c ] = new char[ columns ] ;
//we assign each row with a constant number of columns
如您所知,棋盘基本上可以表示为方阵,因此
Matrix dimension: Row x Column where Row = Column
希望能回答你的问题!
干杯
阿鲁尔·维尔曼
虽然您可以自由地声明和分配指向 char [tRows] 的指针数组,然后为每行循环分配,但您也可以声明指向char [tRows] 数组的指针并在单个调用中分配其中tRows
个,这提供了单个分配和单个可用的好处,例如
#include <iostream>
#include <iomanip>
#define tRows 10
int main (void) {
char (*chessboard)[tRows] = new char[tRows][tRows];
for (int i = 0; i < tRows; i++) {
for (int j = 0; j < tRows; j++) {
chessboard[i][j] = i + j;
std::cout << " " << std::setw(2) << (int)chessboard[i][j];
}
std::cout << 'n';
}
delete[] (chessboard);
}
示例使用/输出
$ ./bin/newdelete2d
0 1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10
2 3 4 5 6 7 8 9 10 11
3 4 5 6 7 8 9 10 11 12
4 5 6 7 8 9 10 11 12 13
5 6 7 8 9 10 11 12 13 14
6 7 8 9 10 11 12 13 14 15
7 8 9 10 11 12 13 14 15 16
8 9 10 11 12 13 14 15 16 17
9 10 11 12 13 14 15 16 17 18
并且,确认您的内存使用情况:
$ valgrind ./bin/newdelete2d
==7838== Memcheck, a memory error detector
==7838== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==7838== Using Valgrind-3.12.0 and LibVEX; rerun with -h for copyright info
==7838== Command: ./bin/newdelete2d
==7838==
0 1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10
2 3 4 5 6 7 8 9 10 11
3 4 5 6 7 8 9 10 11 12
4 5 6 7 8 9 10 11 12 13
5 6 7 8 9 10 11 12 13 14
6 7 8 9 10 11 12 13 14 15
7 8 9 10 11 12 13 14 15 16
8 9 10 11 12 13 14 15 16 17
9 10 11 12 13 14 15 16 17 18
==7838==
==7838== HEAP SUMMARY:
==7838== in use at exit: 0 bytes in 0 blocks
==7838== total heap usage: 2 allocs, 2 frees, 72,804 bytes allocated
==7838==
==7838== All heap blocks were freed -- no leaks are possible
==7838==
==7838== For counts of detected and suppressed errors, rerun with: -v
==7838== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
相关文章:
- 二维阵列的动态分配
- 英特尔并行工作室 2015 C++中的 2D 动态分配全局阵列
- 动态分配'string'阵列
- 如何在C 中创建动态分配的2D结构阵列
- 动态分配的结构阵列具有动态分配的结构阵列元素
- 多阵列动态内存分配错误
- 动态分配的输入,并在C 中输出2D阵列
- 从动态分配的阵列获取内存泄漏
- 在动态分配的多维阵列后清理
- 如何在C++中为灵活阵列动态分配内存
- 正确转发到动态分配的阵列的专用化
- 为动态分配的阵列分配更多内存
- 将动态分配的阵列复制到更大的阵列,而不会发生内存泄漏
- 如何高效地克隆动态分配的阵列
- 如何扩展动态分配的阵列
- 常规 2D 阵列与动态分配的 2D 阵列
- 动态分配的阵列,双释放或损坏
- 动态分配 3D 阵列
- 空函数中的二维阵列动态分配
- 三维阵列动态分配问题