954,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Trying to return a 2D array

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!

Splam Bub
Newbie Poster
3 posts since Feb 2011
Reputation Points: 10
Solved Threads: 0
 

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.

Adak
Nearly a Posting Virtuoso
1,479 posts since Jun 2008
Reputation Points: 425
Solved Threads: 185
 

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 ;)

Splam Bub
Newbie Poster
3 posts since Feb 2011
Reputation Points: 10
Solved Threads: 0
 

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
Splam Bub
Newbie Poster
3 posts since Feb 2011
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: