Function only returns the first elelement of the array

So I'm trying to print out an array that I'm returning from a function. Right now only the first element in the array comes back correctly, the rest of them contain junk. What am I doing wrong?

The relevant code is as follows:

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
int main()
{
	int ticket[6];
		
	*ticket = *menu();

	for(int i = 0; i < 6; i++)
	{
		cout << ticket[i];
	}
};

int* menu()
{
	
	int randomTicketOne[6];

	srand((unsigned)time(0)); 
     
	cout<< "Your numbers are: \n" << endl;
				
	for(int i = 0; i < 6; i++)
	{ 
	randomTicketOne[i] = (rand() % 59) + 1;
	cout << randomTicketOne[i] << endl;
	}
	return randomTicketOne;
}


I've also tried doing it this way and I get the same results:

1
2
3
4
5
6
7
8
9
10
11
int main()
{
	int array[6];

	int *ticket = menu(array);

	for(int i = 0; i < 6; i++)
	{
		cout << ticket[i] << "\n";
	}
};
Last edited on
Your function menu() is invalid since it returns a pointer to a local variable which is destroyed after the function exits. Either pass a valid pointer with enough space into the function or use dynamic allocation.
I was really confused by your answer (apparently I'm really bad at this stuff) but I played around with it based on what you said and it looks like I figured it out! Thanks a bunch! Here's the solution in case it helps anyone in the future:

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
int main()
{
	int *ticket = new int[6];
		
	*generateTicket(ticket);

	for(int i = 0; i < 6; i++)
	{
		cout << ticket[i] << endl;
	}
};

int* generateTicket(int array[])
{
	
	int randomTicketOne[6];

	srand((unsigned)time(0)); 
				
	for(int i = 0; i < 6; i++)
	{ 
	array[i] = (rand() % 59) + 1;
	cout << array[i] << endl;
	}
	return array;
}
Last edited on
Ok you pretty much figured it out. However the important thing you understand is why it works. If you don't, you need to ask more questions.
Well, I understand that arrays (any variable) created inside a function will be destroyed when the function is finished, and what I was doing before was passing back a pointer of the array, which is the first element in the array but when the compiler tried to print the other elements they were already destroyed so I got junk.

Now what I'm doing is creating a dynamic array and the values are put inside the new array at compile time... Actually no I don't understand that at all.

I also don't understand why when I generate multiple tickets all the values are the same..


Update- fixed the random number issue by taking the seed(er) out of the function and putting it in the main.
Last edited on
This'll probably help you a little:
http://www.cplusplus.com/doc/tutorial/pointers/
Topic archived. No new replies allowed.