C++/Question regarding arrays...
Expert: Eddie - 1/20/2008
QuestionQUESTION: Is there a way to set/change the number of elements within an array at runtime? Everything I've done so far gets an error stating that the number of elements within the array has to be a constant. Thanks in advance for your help!
-Neil
ANSWER: Hello Neil, thank you for the question.
Sure, you can do that. The easiest way to allocate at runtime is with a pointer. Here is a simple example:
int numItems;
cout << "Enter the number: ";
cin >> numItems;
int *array = new int[numItems];
// do something with the array
for(int i = 0; i < numItems; i++)
{
array[i] = i;
}
// clean up
delete [] array;
That should have you pointing in the right direction.
I hope this information was helpful.
- Eddie
---------- FOLLOW-UP ----------
QUESTION: Hi Eddie,
In testing your procedure, all went well until I, following your suggestion, tried to delete the array (avoids memory loss, I'd guess), where the program crashed. Removing the deletion allowed the program to run OK. I'm using VisualC++6.
AnswerHello Neil. Thank you for the question.
Whenever you explicitly allocate memory with new, you have to call delete to clean it up, or else you will leak that amount of memory.
If there was a runtime crash with deleting the array, it's probably because something referenced it after it was deleted and memory was corrupted. That is a pretty common crash error with memory allocation. Does it crash exactly on the call to delete?
- Eddie