Click here to Skip to main content
15,913,115 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have written a prgram that return a string.my return type was char??

and i get no output for the progaram .is there any one who can help me do this...what should be the retuen type of the program if it return string of character


What I have tried:

i have tried to return a string with type char...but i know it is wrong.what is the correct type for the program ??
Posted
Updated 21-Jun-18 23:19pm

The common method is to allocate memory for the string using malloc() and returning a char* pointer to that allocated memory. The calling function is then responsible for freeing the memory:
C++
char *SomeFunc()
{
    // Determine required size and allocate
    // Don't forget to add one for the terminating NULL char
    char *buf = (char *)malloc(requiredSize);
    // Write to buf here ensuring that requiredSize is not exceeded

    // Calling function must free the memory
    return buf;
}

In some cases you can also use a static char[] buffer. Then return a const char* to that buffer. But you should know about the possible problems witch such functions (fixed size, not thread safe).
C++
const char *SomeFunc()
{
    static char buf[SOME_FUNC_STATIC_BUF_SIZE] = "";
    // Write to buf here ensuring that SOME_FUNC_STATIC_BUF_SIZE is not exceeded
    return buf;
}

Another solution is passing the buffer and its size as arguments:
C++
char *SomeFunc(char *buf, size_t size)
{
    // Write to buf here ensuring that size is not exceeded
    return buf;
}

With C++, use a C++ string type like std::string instead and return that. Then you don't have to care about freeing memory:
C++
std::string SomeFunc()
{
    std::string buf;
    // Assign to buf here
    return buf;
}
 
Share this answer
 
Comments
dhanarajappu456 22-Jun-18 6:24am    
thank you
At best you return some string object like std:string.

Another solution is to return a char* but it has some problems like
a) the string you allocated needs to be freed elsewhere or your
b) are poiting to a buffer from the function scope and need to make a copy.
C++
char *getStringA()
{
  char * p = new char[12];
  strcyp( p, "hello world");
  return p;
}
char *getStringB()
{
  char p[12];
  strcyp( p, "hello world");
  return p;
}
   //call A
   char *resultA = getStringA();
  // usage
  //cleanup
  delete resultA;
  //call B
   char *resultB = getStringB();
   char buffer[12];// must be big enough
   strcyp( buffer, resultB(
  // usage
  // no cleanup!!!
 
Share this answer
 
Comments
dhanarajappu456 22-Jun-18 6:24am    
thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900