谁能告诉我这个代码片断,请的描述?
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
希望这能回答你的问题!
干杯,
了Arul Verman
尽管你可以自由地声明和分配用于一个阵列的指针到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)