Returning an array from a function

Hello. What I have here is a function that is suppose to return an array of integers. There is a struct array (data1) that holds a first name, last name and the answers to various question( all answers are int data types). I need to look into the struct at index id and return an array of ints that represents the answers.
I have ran a cout test, in the get function, and it prints out the correct answers so I think my for loops are correct but I can figure out how to return the array.
Any help would be great.
Thanks.


int* get( int id )
{
int array1[ 11 ];
for( int i = 0; i < 18; i++ )
{
if( data1[ id ].answers[ i ] == data1[ i ].answers[ i ] )
{
for( int n = 0; n < 11; n++ )
{
array1[ n ] = data1[ id ].answers[ n ];
}
}
}
return ????
}
It's not possible this way, the array is destroyed once the function is finished. You can:
- Dynamically allocate it but the calling function would have to delete it.
- Pass the array as a parameter and only fill it in the function: void get(int id, int* array) but it wouldn't be good style as well
- you could use a class that contains the array (like std::vector): std::vector get(int id)

Edit: kbw was faster to write a right answer than me to correct mine.
Last edited on
It's conventional to pass in the array and its size as in:
 
void get(int id, int* array, size_t sz)


The code you posted is incorrect because when you call get(), an instance of the local variable array1 is created on the stack. When you return, although you return the address of the array, the stack is popped, the array is destroyed, and the memory is used for the next function call. So although you have a pointer, it's pointing to memory that's being rewritten by the C runtime environment.
Thanks kbw and JoR for the help.
Would this work properly if array1 was global? If it will how do I return the value's in the array from the function?
I am limited to what I can change in the function parameters, the function was written by someone else.
Last edited on
The method I suggested passes the array by reference. So the changes are made to the array passed in. There's no explicit return.

Yes, it will work for global, auto or dynamically created arrays.

It's the same method used for standard C library functions like strncpy, memcpy and so on.
Last edited on
Thanks kbw for your time and information.
Topic archived. No new replies allowed.