2015-09-28 84 views
-3
int *tthousand = new int[10000]; 
int *hthousand = new int[100000]; 
static int tmillion[10000000]; 

你好,爲大陣列分配內存? [C++]

我試圖動態地分配存儲器的一系列陣列。這些數組然後填充範圍從0到10,000,000的隨機數。從那裏,他們使用快速排序/選擇排序進行排序。我遇到的問題是,只要達到「tmillion」數組,程序就會運行一段時間,然後發生堆棧溢出。

我試着寫它:

int *tmillion = new int[10000000]; 

和..

static int tmillion[10000000]; 

我必須失去了一些東西簡單。道歉,我對C++還是有點新鮮的。

想法?

+1

你是否檢查'new'的結果呢?你有沒有調試過找到崩潰的來源? – John3136

+1

適合我。 http://ideone.com/qmvKpT –

+2

你總是可以嘗試發佈一個最小但完整的例子。但這對讀者來說可能太簡單了。 –

回答

0

僅供將來參考。由於C++ 11 std :: array是在標準庫中引入的。它應該比C-like內置陣列更受歡迎。

實施例:關於此容器

#include <array> 
std::array<int, 10000000> myArray; 
// fill the array with data 
std::sort(myArray.begin(); myArray.end()); // sorts data using default operator < 

的更多信息可以在Bjarne的主頁上找到:http://www.stroustrup.com/C++11FAQ.html#std-array

標準容器陣列是在定義的元素的一個固定大小隨機接入序列。它沒有超出它需要的空間開銷,它不使用空閒存儲,它可以使用初始化列表進行初始化,它知道它的大小(元素數量),並且不會轉換爲指針,除非你明確地要求它。換句話說,它非常像沒有問題的內置陣列。

附加例如:

#include <array> // std::array 
#include <algorithm> // std::sort 
#include <iostream> // std::cout 

int main() 
{ 
    std::array<int, 10> myArray = {8, 3, 6, 7}; // array with 10 elements but create it with declaring only first 4 elements 

    std::cout << "BEFORE SORT:" << std::endl; 
    for (const auto& element : myArray) 
    { 
     std::cout << element << std::endl; 
    } 

    std::sort(myArray.begin(), myArray.end()); // sorts data using default operator < 

    std::cout << "AFTER SORT:" << std::endl; 
    for (const auto& element : myArray) 
    { 
     std::cout << element << std::endl; 
    } 
} 

輸出:

BEFORE SORT: 
8 
3 
6 
7 
0 
0 
0 
0 
0 
0 
AFTER SORT: 
0 
0 
0 
0 
0 
0 
3 
6 
7 
8 
+0

根據你引用的文字*「它不使用免費商店」* - 所以一個堆棧託管的'std :: array '正如你所說明的那樣,仍然會在典型系統的問題中提到的大小。 –

+1

這是正確的。儘管如此,他仍然可以在堆上分配它,並使用unique_ptr包裝它。 'std :: unique_ptr myArray = std :: make_unique (10000000);' – dptd