二维阵列的动态分配

时间:2018-10-07 05:46:59

标签: c++ multidimensional-array dynamic-memory-allocation

有人可以告诉我此代码段的描述吗?

chessBoard = new char*[ tRows ] ;
for ( unsigned int c = 0; c < rows; c++ )
{
    chessBoard[ c ] = new char[ columns ];
}

问题:

char*[tRows]是什么,其作用是什么?
而且,chessBoard[c]是什么?

请给我准确的描述。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

虽然您可以自由声明和分配指向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)