allocation problem

S

SSJBardock

please help me, 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
 
R

Rolf Magnus

SSJBardock said:
please help me, 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.

std::vector<std::string> m_IDs(m_NumerOfStrings, std::string(500), ' ');

This creates a vector and initializes it with m_NumberOfStrings strings,
which are each initialized to 500 space characters.

If you insist on making your life hard by using arrays and pointers to
char:

char** m_IDs = new char*[m_NumberOfStrings];
for (int i = 0; i < m_NumberOfStrings; ++i)
m_IDs = new char[500];

Note that those char arrays are uninitialized.

Don't forget to delete them:

for (int i = 0; i < m_NumberOfStrings; ++i)
delete [] m_IDs;
delete [] m_IDs;
 
R

Rolf Magnus

Rolf said:
std::vector<std::string> m_IDs(m_NumerOfStrings, std::string(500),
' ');

Of course that must be:

std::vector<std::string> m_IDs(m_NumerOfStrings, std::string(500, ' '));
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,145
Messages
2,570,824
Members
47,370
Latest member
desertedtyro29

Latest Threads

Top