Creating an Array Based on User Input

Hi All,

I am trying to create a variable length array based upon a user's input. I am not sure what I am doing wrong here but when I declare the array I get an "expression must have a constant value" message.

Here is my code..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
String^ filename = "players.txt";

StreamWriter^ sw = gcnew StreamWriter(filename);

int numOfPlayers, numOfRounds, score;

cout << "Enter the number of players: ";
cin >> numOfPlayers;
sw->Write("Number of players: ");
sw->WriteLine(numOfPlayers);

cout << "Enter the number of rounds to play: ";
cin >> numOfRounds;
sw->Write("Number of rounds: ");
sw->WriteLine(numOfRounds);

int playerArray[numOfPlayers];

sw->Close();

return 0;


Can anyone tell me what I am doing wrong?
Last edited on
That doesn't look like C++. Is this some weird Windows CLI thing?
Yes, part of my project here is to write lines to a text file. This is still C++
Yes, part of my project here is to write lines to a text file. This is still C++

This is definitely not C++, but, as in C++, the size of an array must be a compile-time constant.

Line 17 is not legal.
Hi, if you want to create an array using a non-constant variable, then you have to use "dynamic array" allocation.

Simply put, it goes like this:

int *playerArray = new int[numOfPlayers];

The new operator allocates the array on a separate memory pile known as the heap and returns a pointer to that array. You then use the pointer as you would the array name, like:

playerArray[0] = 55;

Otherwise, declaring an array the way you did results in the array being allocated on the stack, which means the compiler needs to know beforehand how much memory to allocate (since it's writing the code to do that). In this case, you can only use constants.
Instead of using an nativ dynamic array you have some better options.

a) use std::array
b) use std::vector
c) use System::Collections.Generic::List
d) use array<int>^
old school C way:

1
2
3
4
int a;
printf("how many");
scanf("%d",a);
int *arry=(int *)malloc(sizeof(int) * a);


you have to catch an address of an int since thats what the name of an array is - you can see we type cast it to just that and catch it in a variable that can hold it then use memory allocate function to access the heap and we say size of int because base on the machine you have it will be a certain number of bytes and you times that by the variable you input - for how many ints you want to store in this block of memory in the heap


dont forget to delete this variable
free(arry);

i would like to refer you to Little Captian's post as this is the C++ way to do it

if you really want to learn - read my post then his

but also the C++ way to delete the memory is delete []a;
you actually have to tell it its an array - don't forget to delete the memory you create
Rusko, thanks for pointing out the delete part! :)
Topic archived. No new replies allowed.