problem with const, string pointers

if i have a class method prototype
const char* gets( ) const
how do i get it to access a (private member) string and return that string?

i have this printf("%s", c.gets()); but it gives me a segmentation fault error at runtime
Last edited on
If your class has a std::string m as a member, then you can have gets return

m.c_str()

The segmentation fault is probably because the C-string that gets is returning is not null terminated.
Or it was the address of a temporary that has gone out of scope. For example:
1
2
3
4
5
6
const char * f() {
    string s = "asdf";
    return s.c_str();
}
//...
const char * p = f(); // Oh noes!  p is dangling because string s went out of scope (doesn't exist anymore). 
Topic archived. No new replies allowed.