Jump to content
  • Advertisement
Sign in to follow this  
gamechampionx

Using char** as string array in C

This topic is 4430 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'm attempting to use char** as an array of strings in C. Basically, I wish to execute something like: char** x = (char**)malloc(4 * sizeof(char*)); I then wish to reference strings by going: x. I'm getting some errors, seeming to do with the malloc usage, and I'm not sure of the correct way of doing this. I know that int* x = (int*)malloc(4 * sizeof(int)); works as expected, so what's the equivalent with char*?

Share this post


Link to post
Share on other sites
Advertisement
I don't see anything wrong with your malloc and a simple test on my system shows no errors.
Though of course remember that each of the char* pointers in your array needs to be allocated storage if you wish to actually use them.
E.g. x[0] = (char*)malloc(10 * sizeof(char));

Share this post


Link to post
Share on other sites
- #include <stdlib.h>.
- Don't cast the malloc result; that's an old way of doing things which is not needed any more (and prevents the compiler from complaining about your not including stdlib.h, which you really should do).
- After allocating the array of pointers, you now have a bunch of random pointer values. You have to point them at meaningful places first before you can do meaningful things with them.

- Please, please forget all of that and use C++ and take advantage of std::string. It is much less painful. Better yet, use something friendlier like Python. Life's too short!

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • 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!