-
Array question
I want to have a 2 dimensional array thats size is determined by user input. I want to do something like this: (declaration)
int array [x] [y];
where x and y are input by the user. But how would I declare this? If I try it like above it tells me constant expected. Any help would be great. Thanks.
-
You need dynamic allocation using new[]/delete[] or to use a container like std::vector.
-
Vectors would be a lot easier, I agree, but I'm doing a project that doesn't allow them. I'm not familar with the other method you mentioned. I'm going to look around and see what I can find on it, but if you wouldn't mind elaborating that would be great.
-
Essentially, you'll have something like this:
Code:
int** array;
array = new int*[x];
for(int i = 0; i < x; ++i)
array[i] = new int[y];
// Use and delete.
for(int j = 0; j < x; ++j)
delete[] array[j];
delete[] array;
Look into pointers and dynamic memory allocation. 'new' allocates a block of memory, and then returns a pointer to it. 'delete' gives that block of memory back.