char* = char[]

Started by
23 comments, last by Staffan E 19 years, 3 months ago

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

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

Output: (null) Whats wrong with my code?
Advertisement
try

char* meh = new char[256];
also, blah isn't initialized to anything...
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
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'.
But is their any way to make keep meh, char* meh?
I'd prefer to keep it char* meh instead of char meh[1024];
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..
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?
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.
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;}
My stuff.Shameless promotion: FreePop: The GPL god-sim.

This topic is closed to new replies.

Advertisement