簡體   English   中英

使用C ++動態分配結構數組

[英]dynamically allocate array of structs with C++

我的問題是我有一個類,它應該采用一個名為“size”的long int,並使用它來動態創建一個結構數組。 以下編譯,但我得到一個運行時錯誤,說明如下:

錯誤“在拋出'std :: bad_alloc'的實例后調用終止what():std :: bad_alloc Aborted

struct PageEntry
{
    ..some stuff in here
};

class PageTable {
public:
    PageTable(); //Default PageTable constructor.
    PageTable(long int size); //PageTable constructor takes arrival time and execution time as parameter
    ~PageTable(); //PageTable destructor.
    PageEntry *pageArray;
};

PageTable::PageTable(long int size)
{
    cout << "creating array of page entries" << endl;
    pageArray = new PageEntry[size];   //error occurs here
    cout << "done creating" << endl;
}

如果我用數字替換“size”,即不會發生錯誤。 10000.有什么想法?

我的猜測是,當你調用函數size某種程度上最終會成為一些可笑的數字或負數。 嘗試在功能中打印出來並告訴我們它是什么。 你可能已經沒有內存了。

另外,請停止使用endl除非您具體指代它而不是'\\n'

尺寸可能為零嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM