Functions returning pointer to array

I have searched this forum but couldn't seem to find a solution. If this has been answered, I apologize.

My function generates an array and then returns a pointer to it. Another function takes this pointer and prints out the array elements.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>

// Prints out array elements
int printArray(int* array, int length)
{
	for(int i = 0; i < length; i++)
	{
		std::cout << "array[" << i << "] = " << array[i] << std::endl;
	}
	
	return 0;
}

int* generateArray()
{
	int array[6];
	int* pointer = array;
	
	array[0] = 13;
	array[1] = 8;
	array[2] = 9;
	array[3] = 10;
	array[4] = 11;
	array[5] = 12;
	
	printArray(pointer, 6);
	return pointer;
}

int main()
{
	int* lotteryNumbers = generateArray();
	printArray(lotteryNumbers, 6);
}


The outcome is:
1
2
3
4
5
6
7
8
9
10
11
12
array[0] = 13
array[1] = 8
array[2] = 9
array[3] = 10
array[4] = 11
array[5] = 12
array[0] = 208
array[1] = 2088824389
array[2] = 2293544
array[3] = 4199448
array[4] = 4486072
array[5] = 4472839


When I call printArray() from inside the generateArray() function, it delivers the correct result. When I call it from main(), it doesn't. What gives?

Thank you for any responses.
I got it! Using dynamic arrays with "new" is the solution. Sorry for the bother :)
The problem with that solution is you have to remember to delete.

In general, you don't return arrays from functions. Instead, you pass them by reference/pointer:

A better way to approach this problem would be as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void generateArray(int array[6])
{
	array[0] = 13;
	array[1] = 8;
	array[2] = 9;
	array[3] = 10;
	array[4] = 11;
	array[5] = 12;
}

int main()
{
	int lotteryNumbers[6];
	generateArray(lotteryNumbers);
	printArray(lotteryNumbers, 6);
	return 0;
}
Thank you, I forgot that you have to delete in C++.

I know that passing by reference is very common in C++, but I just can't seem to get used to it. For me, a function is a subroutine that takes parameters and returns values. But I guess it's my Pascal background talking. Also, I much prefer Perl's approach to the whole pointer/reference thing. Please don't hate me.
Topic archived. No new replies allowed.