So I want to create an array size depending on what the user specifys. I have tried this in visual studio 2010 and it tells me it has to be a constant value. How do I let a user input and define a constant ? :(
the compiler needs to know at compile time what the size of the array is, because it is going to set a block of memory in the local store aside for you to use.
To create arrays dynamically, you need to create memory on the free store, and you do this using the "new" keyword in c++
int* myArray = 0;
myArray = new int[10];
This creates an integer pointer called myarray, and sets the pointer address to the start of the array that the new keyword created.
For this to occur, you need to also free the memory using the keyword delete.
Another option is to declare a static 10x10 array then use only the size x size portion of it that you need.
This is practical because the upper limit for the array size is small.
If you have predetermined sizes for your boards, one option (definitely not the best, but it'll get the job done) is to have three different functions which create your arrays based on the size the user wants. Then, have all of the user's interaction with the program take place in whichever function they chose, going back to main only to exit.
#include <iostream>
void board2();
void board5();
void board10();
int main()
{
int choice;
std::cin >> choice;
if (choice == 2)
{
board2();
}
elseif (choice == 5)
{
board5();
}
elseif (choice == 10)
{
board10();
}
return 0;
}
void board2()
{
int board[2][2];
//rest of code
}
void board5()
{
int board[5][5];
//rest of code
}
void board10()
{
int board[10][10];
//rest of code
}
This definitely isn't your best option, but like I said, it would get the job done, if you can't get anything else to work for a multidimensional array.