Domanda

I have a member function in a class that returns a String. What do I need to do in the declaration if I want to make the return a C-string type? The revised function may or may not have a C-string argument(It is OK to remain the current argument).

The original declaration is :

string function(string argument);
È stato utile?

Soluzione

C-style strings are char arrays closed with a \0, so:

char* function(string argument);

You may also consider tor return a string and retrieve a C-string from that value via the c_str() method.

Altri suggerimenti

C strings are just glorified pointers to first char of the string, with a 0 byte marking end of string. So, you return a char pointer:

char *function(string argument); // returns pointer to modifiable char buffer

The hard part is, string must still exist somewhere. You can not return address of a local variable, for example, because it disappers when the function returns. The low level way is, you return a pointer allocated from heap with new char[length+1] and expect the caller to delete[] it when done with it. But this is prone to memory leaks and all the other fun stuff of manual memory management.

Easier is to return some kind of wrapper object, for example a smart pointer. However, by far easiest and least error-prone is to use std::string as the wrapper object, and access the C string with its c_str() method...


There is one case where returning C string may make sense: you are returning a string literal from a selection of literals, like this crude example:

return (result>0 ? "positive" : "not positive");.

In that case, return pointer to const char, because literals are read only, and do not mix it with anything like returning a generated string in heap (because who will then delete it?).

const char *function(string argument); //returns pointer to string literal

I would declare the function the following way

char* function( const std::string &s );

The cstring header provides functions for dealing with C-style strings — null-terminated arrays of characters.

#include <cstring>
string function(std::string argument);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top