次のC++コードに何か問題がありますか?
int i;
int n;
cout << "a";
cin >> n;
int player[i];
for(i = 0; i <= 3; i++)
{
player[i] = n;
}
次のC++コードに何か問題がありますか?
int i;
int n;
cout << "a";
cin >> n;
int player[i];
for(i = 0; i <= 3; i++)
{
player[i] = n;
}
同じ機能を得るには、次のようにします。
#define PLAYER_SIZE 4
//Or you can go:
//const int PLAYER_SIZE = 4;
int n = 0; //Don't *need* to = 0 in this case, but good practice.
cout << "a";
cin >> n;
int player[ PLAYER_SIZE ];
for( int i = 0; i < PLAYER_SIZE; ++i )
{
player[i] = n;
}
この場合、i<=3 はハードコーディングされているため、4 より大きくする必要はありません。
iを何かに初期化し、それをconstと宣言してから、それを使用して静的配列のサイズを削除しても問題ありません。
実行時にサイズを決定する場合は、new演算子を使用して、ヒープメモリとポインタを処理する必要があります。
const int i = 4; // whatever size
int player[i];
int n;
cin >> n;
cin.ignore(); // important if you plan on using cin again, also think about adding some input checking
for (int x = 0; x < i; ++x ) // for god sakes use ++x
player[x] = n;
// take note your setting every int in player to the same value of n
少しだけきれいにするために
const int arraySize = 4;
int playerArray[arraySize];
int input = 0;
for ( int i = 0; i < arraySize; ++i )
{
cin >> input;
cin.ignore(); // still no error checking
playerArray[i] = input;
}
このコードを使用すると、配列内のintごとに異なるintを入力できます。
you can't declare index of array as variable
のように、いくつかのサイズを宣言します
int player[10];
またはプリプロセッサ ディレクティブを使用する
#define i 10
int player[i];
完全に
#define i 10
int main()
{
int j;
int n;
cout<<"a";
cin>>n;
int player[i];
for(j=0;j<=3;j++)
{player[j]=n;}
}