0

Anything wrong with the following C++ code?

int i;
int n;
cout << "a";
cin >> n;
int player[i];
for(i = 0; i <= 3; i++)
{
     player[i] = n;
}
4

3 回答 3

1

To get the same functionality, I would do:

#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;
}

Since i<=3 is hard coded in this case, there's no need to go any higher then 4.

于 2012-09-26T03:24:19.367 回答
0
you can't declare index of array as variable

declare some size, like

int player[10];

or use preprocessor directives

#define i 10
int player[i];

totally

#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;}
}
于 2012-09-26T02:50:29.703 回答
0

Initialize i to something and declare it const then using it to delcare the size of a static array is ok.

If you want the size to be determined at run time you will need to use the new operator and deal with heap memory and pointers.

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

Just to clean it up a little

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;
    }

This code allows for different ints to be inputted for each int in the array.

于 2012-09-26T03:43:55.357 回答