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.
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;
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 = newint[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.
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