Functions that return a string

Started by
3 comments, last by drsixstring 22 years, 1 month ago
This doesn''t work:
  
char[5] GetString()
{
  char str[5] = "hello";
  return str;
}
  
How would I write a function that would return a string?
Advertisement
quote:Original post by drsixstring

This doesn''t work:

    char[5] GetString(){  char str[5] = "hello";  return str;}    


How would I write a function that would return a string?

    char* GetString(){  char str* = strdup("hello");  return str;}    


there isnt any way to maintain the integrity of an arrays size, at compile time, without actually stating it.

so you may need to pass a byref length argument.

void getArray(char str[], int &length);

often, a string will be NULL terminated, meaning the last character in it is 0.

void getArray(char zStr[]);

if you want to return an array, then you use char*
char* getArray();
If you''re not adverse to c++ and the stl:

#include <string>using std::string;string GetString(){  string str="hello";  return str;} 
Thanks guys, that helps a lot. Soon after I posted I realized I would need to use a pointer. But Sjelkjd''s info on the string class in C++ will be something I''ll have to check out.

This topic is closed to new replies.

Advertisement