二维阵列的动态分配

Dynamical allocation of 2D-array

本文关键字:阵列 动态分配 二维      更新时间:2023-10-16

有人可以告诉我这个代码片段的描述吗?

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)