function that reads a char array

Hi Experts,

I thought I knew this, but I am getting confused now.  I need to return an array of strings to a caller.
How can I do it.  The following code works, but the caller has to know the size.  If I want the function to return any number of items, how can I do it. ( can you please provide example both using strings and char *)
Thanks.

void getArray(char* a[])
{
	a[0] = "one";
	a[1] = "two";
	a[2] = "three";
	a[3] = "four";
        a[4] = "five";
}

int main() 
{
	char * arr[5];

	getArray(arr);

	for( int  i = 0; i < 5; i++ )
	{
		cout << arr[i] << endl;
	}
	getchar();
}

Open in new window

ambuliAsked:
Who is Participating?
 
evilrixConnect With a Mentor Senior Software Engineer (Avast)Commented:
Just return std::vector<std::string> by value.
0
 
jkrConnect With a Mentor Commented:
evilrix pretty much has covered what it takes to do that with a std::string, if you still need it for char*, just allocate the space you need:
#define OUT_ARRAY_SIZE 5 // I assume you get the actual size at runtime

unsigned int getArray(char** a)
{

        a = (char**) malloc(OUT_ARRAY_SIZE * sizeof(char*));

	a[0] = "one";
	a[1] = "two";
	a[2] = "three";
	a[3] = "four";
        a[4] = "five";

        return OUT_ARRAY_SIZE;
}

int main() 
{
	char** arr;

	unsigned int count = getArray(arr);

	for( int  i = 0; i < count; i++ )
	{
		cout << arr[i] << endl;
	}
	getchar();

        free(arr);
}

Open in new window

0
 
ambuliAuthor Commented:
Thank you.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.