Is it possible for a function to return a string,an array of characters to the calling function?
i mean something like
char f1()
char www="nima";
if not,please tell me how is this possible?

8 Years
Discussion Span
Last Post by ArkM

There are a several ways to return a string to a calling function. You can use char* or the C++ string class.

I would recommend:

int foo(char* myString){


  return 0;
int foo(string& myString){
    myString = "www";
  return 0;

You can also do

char* foo(){
  char* myString = strdup("www');

return myString;
string& foo(){
  string myString = new string[SIZE];
  myString = "www";

  return myString

If you are going to use char* or string& or string* as the return type for a function, then please be very careful that you do not try to return the address of a local variable, because as soon as you return from the function, it will cease to exist, and you will end up with garbage. And make sure you free any allocated space for the string when you are done using it.


stilllearning's third example could lead to problems, as you're allocating memory in the function, and may not remember to delete it later.

The fourth example doesn't need the address of operator, just return the string. It doesn't need to be created with the new operator, string objects will size themselves to the content assigned.

string foo(){
  string myString =  "www";

  return myString

Alas, do not use all stilllearning's methods (sorry, stilllearning ;)).
The safe method:

std::string foo(.......) { // not string& !!!
    char buf[...];
    // form buf contents
    return buf; // don't worry: it returns string object
// or if you don't know max buf size
std::string bar(.....) {
     std::string str;
     // form str contents
     return str;

Another (C style) approach - use fgets style (Ancient Dragon's advice in the recent thread):

char* foo(char* buff, int bsize, ......) {
    // Use callee's C string buffer[bsize]
    return buff; // get its address back

Apropos, correct the monstrous code of the original snippet:
1. Your f1 returns char (not char array)
2. You declare char www (not char array)
3. You return an invalid pointer to a local variable.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.