动态内存分配:当最右边的维度是可变的时,二维数组的替代方案是什么

Dynamic Memory Allocation: What is the alternative for a two dimensional array when the rightmost dimension is variable?

本文关键字:二维数组 是什么 方案 分配 内存 动态 右边      更新时间:2023-10-16

我正在尝试开发一个类来备份和恢复控制台屏幕缓冲区。这是我正在进行的代码。

class CBuff
{
private:
    CONST WCHAR max_unit;
    HANDLE hnd;
    CHAR_INFO *stor_buff;
    COORD s_buff_sz;
    COORD d_buff_cod;
    SMALL_RECT read_region;
public:
    CBuff():max_unit(10)
    {}
    ~CBuff(){}
void Initiate(HANDLE hndl, SHORT buff_x, SHORT buff_y, SHORT buff_width, SHORT buff_height)
{
    hnd=hndl;
    stor_buff=new CHAR_INFO[buff_width*buff_height]();
    s_buff_sz.X=buff_width;
    s_buff_sz.Y=buff_height;
    d_buff_cod.X=0;
    d_buff_cod.Y=0;
    read_region.Left=0;
    read_region.Top=0;
    read_region.Right=buff_width-1;
    read_region.Bottom=buff_height-1;
}
int Backup()
{
    if(!ReadConsoleOutput(hnd,stor_buff,s_buff_sz,d_buff_cod,&read_region)) return -1;
    return 0;
}
int Restore()
{
    if(!WriteConsoleOutput(hnd,stor_buff,s_buff_sz,d_buff_cod,&read_region)) return -1;
    return 0;
}
int Backup_mp()
{/*incomplete*/}
int Restore_mp()
{/*incomplete*/}
};

它与 Backup() 和 Restore() 配合使用很好。然后我尝试制作另一个版本的备份,Backup_mp(handle, backup_num),它将从不同的控制台缓冲区实例创建多个备份。我计划将私有空间中的最后四个变量转换为数组,以便索引值 (backup_num) 可用于不同的备份点。像这样的分配

stor_buff=new CHAR_INFO[index][buff_width*buff_height]();

不工作。

我有什么选择?

另外,我可以使用 CONST WCHAR max_unit 作为像 s_buff_sz[max_unit] 这样的数组的参数吗?

你正在使用C++,所以要利用它:使用 std::vector。

//Declaration of your buffers:
std::vector< std::vector<CHAR_INFO> > store_buffers;
//Append a new buffer entry:
store_buffers.push_back( std::vector<CHAR_INFO>( buff_width * buff_height ) );
// Pass buffer with index index to WinAPI functions:
..., store_buffers[index].data(), s_buff_sz, ...

如果使用 C++11,则可以将 std::array 用于固定大小的维度(而不是可变的 std::vector),但这并不重要。

要在堆中分配二维数组(使用 new ),您需要先分配指针,然后再分配数组。例:

stor_buff = new CHAR_INFO* [buff_height]; // Allocate rows (pointers
for(int index = 0; index < buff_height; ++index)
   stor_buff[index] = new CHAR_INFO[buff_width];

并直接使用它们,就好像store_buff是 2D 数组一样。对于释放,您需要先删除数组(即单个行),然后再删除行指针。

  for(int index = 0; index < buff_height; ++index)
        delete []stor_buff[index];   // NOTICE the syntax
    delete []stor_buff;

或者,您可能有一个一维数组,将其用作 2D。为此,您需要进行(row,col)计算才能获得所需的元素。

您也可以使用 vector(或vector vector ),以获得相同的结果。但我建议你玩原生指针,除非你习惯了指针!