2013-01-24 13 views
2

我正在嘗試開發一個類來備份&還原控制檯屏幕緩衝區。這是我的代碼正在進行中。動態內存分配:當最右邊的維度可變時,二維數組的替代方法是什麼?

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]這樣的數組的參數嗎?

回答

1

您正在使用C++,因此請使用它:使用std :: vector。使用C++ 11

//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, ... 

如果,可以使用std ::陣列用於固定大小的尺寸(而不是標準::載體,它是可變的),但是這不是關鍵的。

+0

非常感謝。我是初學者,對STL還不太清楚。但是,我會嘗試。 – Shakil

0

要在堆中分配一個二維數組(使用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是二維數組。對於重新分配,您需要首先刪除數組(即單個行),然後再刪除行指針。或者,你可能有一個一維數組,使用它作爲二維數組。爲此,您需要執行(row,col)計算以獲取所需的元素。

您也可以使用vector(或vectorvector),以獲得相同的結果。但我建議你玩本土指針,除非你習慣了指針!