Hey guys,
I've done some google searches today but didn't find a clear cut answer to this. I've got a function that I would like to return an array of strings. Any ideas anyone?

You could use char** as the return type, and pass in an integer pointer that will hold the total number of strings that you return to the calling function.

for example:

char** foo (int* nStrings, ....)

I'm a bit rusty when it comes to pointers. char ** is a pointer to a pointer?

yes a char** is a pointer to a pointer.

Basically a char* can be used to define a array of characters or a string. And a char** is used to define an array of strings.

You could write something like this to allocate and populate a char**

p2StrArray = (char**)malloc(*sizeofarray);

  for (i = 0; i < *sizeofarray; i++){
    p2StrArray[i] = (char*)malloc(sizeofstring); /* can use strdup instead of malloc here */ 
  }

If you are not comfortable with pointers, and familiar with the C++ STL, you could use something like this

int returnCppStrings(vector<string>& strArray){ }

One thing I would suggest is that instead of returning a pointer to the array of strings, pass it in as an argument from the calling function as shown above with the vector. Its a safer convention.

Thanks. Currently I'm using a variable of the type 'string' - I'm assuming I can't work with that one if I want arrays?

You could use a string with the C++ STL vector, as I showed above.

Here is a tutorial that explains vectors some more, with an example.

http://www.yolinux.com/TUTORIALS/LinuxTutorialC++STL.html

Or you can use a function like this. Make sure that you delete all the pointers you allocate.

/* define your array */ 
string* myCppStrings;
/*allocate space for it */
myCppStrings = new string[sizeofarray]; 

.................

int returnCppStrings(string* strArray, int sizeofarray){
  
  int i;

  for (i = 0; i < sizeofarray; i++){
    strArray[i] = "string";
  }

  return 0; 
}
This article has been dead for over six months. Start a new discussion instead.