Hello DaniWeb! I'm trying to return an array of strings from a function but I'm not sure how to do so. I've done the prerequisite Googling and have found people on this discussion board recommending to return char** which, it is said, can then be converted back into 2d array notation. It is this conversion to and from char** which has confused me and I have not been successful in clarifying this for myself, so my question is this:

How may I represent a 2D array in a fashion that can be returned as char**, and how would I re-convert this to 2D array representation once I have returned it?

Thank you for reading!

It's easier if you create the array in the calling function, then pass it into the called function as a parameter. Upon return from the called function, the array is still valid, and has the data you want in it.

You can do it the other way, but it's more work.

commented: Nice and helpful. +0

This is a very good idea, and I hadn't thought of it. I did wonder why most of the library functions do it this way, and I now have an answer!

I shall leave this thread unsolved for now so that if I run into problems while trying to implement your suggestion, I won't clutter the forum up with a new topic. When I succeed, I shall mark as solved ;)

Solved! Sorry for the delay.

Your solution worked very well, although I did have to do some research to understand why having "char param[][]" in the signature isn't legal in C. This is what I get for being green :)

Here's the test code I used, for those who come across this thread again via Google or otherwise:

#include <string.h>
#include <stdio.h>

static char arr[2][30] = {"hellotest1", "supbrotest2"};



int dothings(char sa[][30], char ma[][30])
{
	int i=0;
	while( strcpy(&ma[i][0], &sa[i][0])  &&  i++ < 2 );
	
	return 0;
}



int main()
{
	char mainarr[2][30];

	dothings(arr, mainarr);

	puts(&mainarr[0][0]);
	puts(&mainarr[1][0]);
	
	return 0;
}

Expected output:

hellotest1
supbrotest2
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.