Click here for important information about

returning an array of character pointers?

February 15, 2011 at 12:30:22
Specs: Windows 7
Is it possible to return an array of character pointers:
>char*[] makeArray()
> char* input[5]={1,2,3,4,5};
> return input;

See More: returning an array of character pointers?

February 15, 2011 at 13:35:52
I don't believe that will work. The array that you declare within makeArray() is stored in the stack frame. Once the function returns that stack frame is no longer valid, so the pointer you return will not be pointing to anything meaningful.

I think a better approach is to pass a pointer (or a pointer to a pointer, or whatever you require) as an input parameter to the function and then manipulate that pointer within the function. Be very careful about memory allocation to ensure that it is still valid when you exit the function.

Report •

February 15, 2011 at 14:41:14
how would i pass a char* input[]

do i need an '&' infront of input[] in the functions parameters:

void makeArray( char* &input)?
void makeArray( char &input[])?
void makeArray( char* &input[])?

Report •

February 15, 2011 at 23:27:55
In answer to your question in reply #2, if char *input[] is defined something like:

char *input[MAX_LINES]

the function call would be:

void makeArray( char* input[])

so, no you do not need the &.

Report •

Related Solutions

February 15, 2011 at 23:29:09
Why not just pass a pointer?
char *makeArray() {
  char *newArray = new char[5]; //Assuming C++
  for (int i = 0, i < 5, ++i) newArray[i] = i;
  return newArray;

Better question if it's C++: Why not just use vector or string?

How To Ask Questions The Smart Way

Report •

February 16, 2011 at 00:52:06
I'd prefer to create the array outside the function rather than within it. That way it's easier to keep track of the size of the array. If you create the array within the function I think it would be good practice to also return a paramater containing the size of the array created.

Report •

Ask Question