Jump to content
  • Advertisement
Sign in to follow this  
Zeophlite

char* = char[]

This topic is 4944 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

char blah[255];
blah = "foobar";
char* meh;

sprintf(meh,"%s",blah);
printf("%s",meh);

Output: (null) Whats wrong with my code?

Share this post


Link to post
Share on other sites
Advertisement
The code:

char blah[255];
blah = "foobar";
char* meh;

sprintf(meh,"%s",blah);
printf("%s",meh);


Is not correct! I'm suprised it does not crash. Here is an alternative:

char blah[255];
sprintf(blah,"foobar");
printf(blah);

the variable meh serves no purpose in this example - it is used as a temporary buffer but it is not sized so it will not work. If you wanted the orig code to work right:


char blah[255];
sprintf(blah,"foobar");
char meh[1024]; // large over kill buffer :)

sprintf(meh,"%s",blah);
printf("%s",meh);

As a side note - you are probabally using Debug mode - which initilizes everything to 0. If you try it in release mode it would crash undoubtedly. I hope this helps some!

- Drew

Share this post


Link to post
Share on other sites
char[] == char*
Except for the fact that a char[] is a pointer which will always point to a correct emplacement containing memory for the array, while your char*, by default, does not point anywhere unless you allocate memory with 'new'.

Share this post


Link to post
Share on other sites
As mike25025 showed, you must allocate some memory if you want to store data through "meh"
char* meh = new char[256];

And don't forget to delete[] it..

Share this post


Link to post
Share on other sites
I see,

In that cases, how do I set the function type for a function that returns a char array:

char meh() {
char goo[12];
...
return goo;
}

What would I change "char meh() {" to, to allow it to return a char array?

Share this post


Link to post
Share on other sites
char *meh()
{
char MyChar[12];
//..
return MyChar;
}


That would be the syntaxically correct function, though, returning a local variable might not be a good idea.

Share this post


Link to post
Share on other sites
Use std::string instead. Seriously. You're just asking for trouble, otherwise.


std::string meh() {
std::string ret_val;
// Assign ret_val in here somewhere.
return ret_val;
}

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!