You are here:

C++/Question regarding arrays...

Advertisement


Question
QUESTION: 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.

Answer
Hello 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

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Eddie

Expertise

I can answer questions about the C++ language, object oriented design and architecture. I am knowledgable in a lot of the math that goes into programming, and am certified by ExpertRating.com. I also know a good deal about graphics via OpenGL, and GUIs.

Experience

I have completed numerous games and demos created with the C++ programming language. Currently employed as a software engineer in the modeling and simulation field. I have about 7 years experience.

©2016 About.com. All rights reserved.