-
Why the error
Hi im kinda new to c++ and I can't seem to fix this compile error.
insert
Code:
char String::c_str()
{
char* cs;
cs = new char[length+1];
strcpy(cs,first);
return cs;
}
I am trying to make a function that takes a String and converts it into a c-style string.
I keep getting this error though " invalid conversion from 'char*' to 'char'"
How come this happens and how can it be fixed.
Thank you all who attempt to help.
-
Code:
char String::c_str()
{
char* cs;
cs = new char[length+1];
strcpy(cs,first);
return cs;
}
There's your invalid conversion.
The idea that a c_str function should allocate an unmanaged string buffer doesn't look good, though.
More commonly this should look like:
Code:
const char* String::c_str() const
{
return first;
}
All the const's so that the user wouldn't be able to mess around with the internal buffer.
If they now want to store that into a dynamically allocated char array, that's entirely up to them to do in the calling code.
Otherwise, most often you'd use the c_str method like this:
Code:
String s("filename");
std::ofstream fout(s.c_str());
When done your way, that would be a memory leak.
-
Your return type should be char * for this function as that is the type of cs.
Are you sure you want to return a copy like that? It could be hard to know when cs was deallocated. Make sure you don't leak memory in your string class!
-
Works no problem
Thank you both for the help. It is working fine now.