I have made a program that dynamically allocates memory to hold several c++ string. There were no problems during compile time. But during runtime I always get a message box telling me that my program has stopped running.
I've observe that when I try to change or print the contents of the 2nd up to the last string element I always get that runtime error.
I have pasted the code of my program here. I wish you can compile it then try running it to check if you dont get any runtime errors.
...
int main()
{
unsigned n=2;
string *numbers = new (nothrow) string[ n ];
if (numbers == NULL)
{
cerr << "Error allocating memory" << endl;
return 1;
}
for (unsigned i=0; i<n; i++)
numbers[ n ] = "kingkoy ";
delete[] numbers;
return 0;
}
See this site for more information on new and delete: http://www.cplusplus.com/doc/tutorial/dynamic.html
See the C++ FAQ Lite for more on why to use new and delete instead of malloc and free: http://www.parashift.com/c++-faq-lite/freestore-mgmt.html
If you want "numbers" to be a dynamic array, you would be better off using one of the STL container types, like vector.
Hope this helps.
[EDIT] Oh yeah, watch your array subscripts.
[EDIT#2] Hmm, I just realized that the realloc thread was yours also. Give yourself a gold star for using google so well... ;-)