Jump to content
  • Advertisement

Archived

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

KevinG

Dynamically allocating strings...

This topic is 5315 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
And to delete I would do "delete[] strings", right?
EDIT: Or would I have to delete strings individually?

[edited by - KevinG on January 25, 2004 3:05:45 PM]

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

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!