2016-10-13 12 views
-2

これまでの議論から検索してきましたが、配列には一定の値が必要ですが、変数に定数値を代入していることを理解していますワーキング。私はこの論理に助けが必要です。私が信じる問題は、私の関数宣言にあります。 Error messasgeは「式には一定の値が必要です」というメッセージが表示されます。ここでコードが...関数宣言で配列に問題があります

// Jason Delgado 
// 10/13/16 © 
// Chapter 9: Array Expander 

// This program has a function that doubles the size of an array. 
// It copies the contents of the old array to the new array, and 
// initializes the unused elements to 0. The function then 
// returns a pointer to the new array. Pointer notation 
// must be used for the function, and within the function. 

#include <iostream> 
using namespace std; 

// Function protoype 
int *arrExpander(int[] , int); 

int main() 
{ 
    // Create and initialize and array. 
    const int SIZE = 6;   // Number of elements the array is to hold 
    int oArr[SIZE] = { 10, 28, 34, 
    5, 18 };      // The original array 

    int *nArr = nullptr;   // A pointer to hold the return value of the function. 

// Call the arrExpander function and store it in nArr. 
nArr = arrExpander(oArr, SIZE); 

// Display the results 
cout << "Original Array: "; 
for (int count = 0; count < (SIZE); count++) 
    cout << oArr[count] << " "; 
cout << "\n\nNew Array: "; 
for (int count = 0; count < (SIZE * 2); count++) 
    cout << *(nArr + count) << " "; 

system("pause"); 
return 0; 

}

int *arrExpander(int arr[], int size) 
{ 
    int *ptr = arr; 
    const int DSIZE = size * 2;  // Doubles the size parameter 
    int newArray[DSIZE]; 



} 
+0

問題は、コードが 'new'を使用して配列を割り当てる必要があることです。これは宣言とは関係ありません。 –

+0

newArray [DSIZE]はコードの残りの部分にどのような影響を与えますか? –

+0

@SamVarshavchikこれはまれな提案です。 –

答えて

0

だ、それが作成された後

const int DSIZE = size * 2; 

に割り当てられた値を変更することはできませんが、それはsizeどの非一定の値に依存しますそして、おそらく関数の名前を指定すると、arrExpanderへのすべての呼び出しで異なることがあります。

int newArray[DSIZE]; 

でコンパイラは、サイズスタックをすることができ、コードを最適化するようにプログラムがコンパイルされるとき、配列の大きさ、DSIZEは、既知であり一定であることが要求されます。関数の呼び出し時に値を変更できる場合は、コンパイル時には定数であることが知られているので、コンパイラはこのコードを無効として正しく拒否します。

一部のコンパイラでは、可変長配列が可能ですが、標準ではないため、すべてのコンパイラでは期待できません。多くの短所とより安全なソリューションのために、サポートが標準に追加されることはありません。可変長アレイの一般的な姿勢は「なぜなら?Use std::vector instead.

これは、このコードが既存の配列のサイズを増やすことを意図しているという匂いも持っています。それはできません。 newArrayはローカル変数であり、関数から戻ってきて、もはや有効ではないメモリへの参照である "ダングリングポインタ"を残して破棄されます。このメモリを使用し続けるには、std::vectorを使用するか、new[]を持つ動的に割り当てられたポインタとしてnewArrayを割り当て、不要になったときには配列delete[]を覚えておいてください。

See std::unique_ptrメモリ管理ヘルパー用。

関連する問題