Archived

This topic is now archived and is closed to further replies.

KevinG

Dynamically allocating strings...

Recommended Posts

I know you can create a string by doing something like this: char * c_ptr = "Hello!" And I know you can create arrays of strings doing this... char *c_ptr[3] = {"Burgers", "French Fries", "Pizza"}; But how do you dynamically allocate strings? Like this? char **strings = new char*[12]; The syntax just seems...odd. Thanks for any help.

Share this post


Link to post
Share on other sites
If you are using C++, then take a look at the standard library
std::vector < std::string >   
will do exactly what you want

[edited by - noVum on January 25, 2004 4:41:20 PM]

Share this post


Link to post
Share on other sites
Thanks, but I was trying to avoid that so I can see exactly how it would work (for better understanding). Is there a way for me to do it without a predefined class or function? Like some raw code I could look at?

EDIT: Yep, C++

[edited by - KevinG on January 25, 2004 2:00:30 PM]

Share this post


Link to post
Share on other sites
char **strings = new char*[12];

This allocates an array of pointers to char

char *string = new char[12];

This allocates a string

And if you want to allocate something like this

char *c_ptr[3] = {"Burgers", "French Fries", "Pizza"};

Then you need to allocate each substring in turn

char **strings = new char*[12];

strings[0] = new char[len0];
strings[1] = new char[len1];
strings[2] = new char[len2];
...

Share this post


Link to post
Share on other sites
You would need to delete[] each string individually (because each is a separate allocation of a char[]), and then delete[] the main array of char* pointers. As a general rule, [] is kind of like * except that it implies that the space is already allocated and won''t change its location.

But it''s exactly because of how tricky all of this is, that you should be using std::string instead.

Share this post


Link to post
Share on other sites