-
allocation problem
I'm rewriting a program I made before because I lost the
source and I want to allocate a number of text strings that are 500 characters long.
So I tried this:
char *m_IDs[500]=(char *)malloc(m_NumberOfStrings);
That obviously doesn't work, but I can't remember how to do it.
Thanks in advance,
SSJBardock
-
Since your using C++ it is prefered to use new.
Code:
// allocate an array of pointers to char*
char** m_IDs = new char*[m_NumberOfStrings];
// allocate memory for each one
...
m_ID[i] = new char[nLengthOfString];
...
delete [] m_ID[i];
...
delete [] m_ID;
-
Thanks, that almost works, but for some reason when I make m_NumberOfStrings higher than 1015 (nLengthOfString being 500) I get an assert error.
Do you have any idea what's the problem and how to fix it?
-
I can't say for sure, but in any case you're trying to allocate half a megabyte in that statement ;)
But since this is C++ and you're using an array of c-strings, I suggest you try using a std::vector of std::string's. Just a suggestion :) Generally in C++, vectors are preferred over arrays since they can do pretty much everything arrays can but easier and in many cases better, and strings are preferred over char* for the same reason.
Code:
#include <vector>
std::vector<std::string> m_IDs;
m_IDs.push_back("SomeID");
m_IDs.push_back("SomeOtherID");
for(int i = 0; i < m_IDs.size(); ++i)
{
doSomething(m_IDs[i]);
}