2017-01-15 2 views
-1

整数を動的配列に保持する方法はありますか?最初に、私は配列の数のinout量をユーザーに尋ね、それらのすべてをそこに保管する必要があります。要素を動的配列に保持する

int n; 
cout << "Enter the number of integers: "; 
cin >> n; 
int input; 
int* array; 
for(int i = 0; i < n; i++){ 
    cout << "Enter your integer:" << endl; 
    cin >> input; 
    array = new int[input]; 
} 
for(int i = 0; i < n; i++){ 
    cout << array[i] << endl; 
} 

最後に一部のゴミ値が表示されます。どうしましたか?

+0

ヒント:このプログラムの正しいバージョンでは、 'new'は、ループ内では表示されません

あなたのプログラムは次のようにする必要があります。 – zwol

+0

まだ動作しません – user7332667

+0

C++で配列を使う方法は明らかです。まずいくつかを読んで、本当の問題を取り戻してください。 – pSoLT

答えて

1

(動的)配列のnewの意味を誤解しているようです。 array = new int[input];を使用して、これが新しいスロットを配列に追加し、値をinputに設定するかのようにします。

二つのステップ実行します、とすぐに、配列が保持するものとどのように多くの項目を知っているとして、そのための予備のメモリを

まず(例えばのようなarray = new int[amountOfValues])。

次に、入力した値ごとに配列の正しい位置に配置します(例:array[i] = someValue; iamountOfValues未満であることを確認してください)。

0

少なくとも3つのアプローチがあります。最初のものは、第1は、以下の

int n; 
cout << "Enter the number of integers: "; 
cin >> n; 
int input; 

int* array = new int[n]; 

for(int i = 0; i < n; i++){ 
    cout << "Enter your integer:" << endl; 
    cin >> input; 
    array[i] = input; 
} 

for(int i = 0; i < n; i++){ 
    cout << array[i] << endl; 
} 

// ... 

delete [] array; 

ある

#include <memory> 

//... 

int n; 
cout << "Enter the number of integers: "; 
cin >> n; 
int input; 

std::unique_ptr<int[]> array(new int[n]); 

for(int i = 0; i < n; i++){ 
    cout << "Enter your integer:" << endl; 
    cin >> input; 
    array[i] = input; 
} 

for(int i = 0; i < n; i++){ 
    cout << array[i] << endl; 
} 

を以下そして3つ目は、単にあなたがあなたの番号を入れしようとしている以下の

#include <vector> 

//... 

int n; 
cout << "Enter the number of integers: "; 
cin >> n; 
int input; 

std::vector<int> array(n); 

for(int i = 0; i < n; i++){ 
    cout << "Enter your integer:" << endl; 
    cin >> input; 
    array[i] = input; 
} 

for(int i = 0; i < n; i++){ 
    cout << array[i] << endl; 
} 
0

あなたの問題であり、値を配列のサイズに変換し、配列の中にそれらを格納しません。

また、各反復では、あなたが入力して配列を初期化がarray = new int[input];

値ので、それはあなたの入力値に応じて各反復でメモリのサイズを確保し、あなたは配列が結果があるため、メモリからゴミ値になる値印刷するとき配列に値を格納していませんでした。

int n; 
cout << "Enter the number of integers: "; 
cin >> n; 
int input; 
int* array; 
array = new int[n]; 
for(int i = 0; i < n; i++){ 
     cout << "Enter your integer:" << endl; 
     cin >> input; 
     array[i] = input; 
} 
関連する問題