2016-11-08 48 views
0

我正在處理一個程序,用戶不斷輸入數字,當數組已滿時,它將保存到數組中,我試圖將原始數組複製到一個新數組中,並繼續填充該數組,但我不能讓它工作。這裏是我的代碼到目前爲止試圖動態增加數組的大小

#include <iostream> 
#include <stdio.h> 
#include <string.h> 
using namespace std; 

int main() 
{ 
    int size; 
     cout << "Please enter how many numbers you want to enter: "; 
    cin >> size; 
    double *array = new double*[size]; 
    cout << "Please enter your numbers: "; 
    for(int i = 0; i < size; i++) { 
     cin >> array[i]; 
     if(i == size-1) { 
      int newSize = 2*size; 
      double *arrayb = new double*[newSize]; 
      for(int i = 0;i<size;i++) { 
       arrayb[i] = array[i]; 
      } 
      delete [] array; 
      array = arrayb; 
      size = newSize; 
     } 
    } 
} 
+6

改爲使用['std :: vector'](http://en.cppreference.com/w/cpp/container/vector)。 – TartanLlama

+3

表達式'new double * [size]'將'size' *指針*數組分配給'double'。在32位系統上這會導致麻煩。 –

+1

請詳細說明您的問題? *你怎麼能不「讓它工作」?請[閱讀關於如何提出好問題](http://stackoverflow.com/help/how-to-ask)。 –

回答

0

我可以得到它通過使在雙打雙指針指向編譯,而不是雙指針數組,

int size; 
cout << "Please enter how many numbers you want to enter: "; 
cin >> size; 
double *array = new double[size]; 
//      ^--- not pointers to doubles 
cout << "Please enter your numbers: "; 
for(int i = 0; i < size; i++) { 
    cin >> array[i]; 
    if(i == size-1) { 
     int newSize = 2*size; 
     double *arrayb = new double[newSize]; 
     //       ^--- not pointers 
     for(int i = 0;i<size;i++) { 
      arrayb[i] = array[i]; 
     } 
     delete [] array; 
     array = arrayb; 
     size = newSize; 
    } 
} 

你有在數據的第一個新內存中分配了足夠的內存。 但是當你在size的當前值結束之前得到一個值時,你分配的空間加倍。並製作size = newSize。 外部for循環將永遠不會結束,除非拋出異常,例如最終發生的bad::alloc

1

如果在執行之前不知道集合的最大大小,您需要避免數組。像TartanLlama說的,你可以使用std :: vector。 Vector允許您儘可能多地添加項目。 但是有很多不同的訪問方法的容器。看到這個鏈接有如何選擇你的容器中的第一視圖: In which scenario do I use a particular STL container?

+0

你應該選擇一個合適的容器。 http://stackoverflow.com/questions/471432/in-which-scenario-do-i-use-a-particular-stl-container – alirakiyan

0

如果你讀了編譯錯誤,你會看到這個問題:

g++ -std=c++17 -fPIC -g -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -O2 -Weffc++  14226370.cpp -o 14226370 
14226370.cpp: In function ‘int main()’: 
14226370.cpp:11:37: error: cannot convert ‘double**’ to ‘double*’ in initialization 
    double *array = new double*[size]; 
            ^
14226370.cpp:17:49: error: cannot convert ‘double**’ to ‘double*’ in initialization 
      double *arrayb = new double*[newSize]; 

你正在創建的指針數組將翻一番,試圖初始化一個指針翻番,兩個案例。

看着你使用這些的方式,你可能打算寫new double[size]new double[newSize]