Pointer saving one element only

I'm trying to make a program that allows the user to display a list of students with a specified gender. It asks the user to enter the gender and this function will return the indexes of all students with the specified gender. It must return a pointer. However, in my solution the pointer stores only one element and I can't figure out out.What am I doing wrong here?
This is my code:

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
35
36
37
38
39
int * resultsByGender( char &gen_choice, const char gen[], const int size)
{
	cout << "Enter gender: (F/M)";
	cin >> gen_choice;

	gen_choice= toupper(gen_choice);

	while((gen_choice!='F')&& (gen_choice!='M'))
	{
		cout << "Error! Invalid choice!\n";
		cout << "Enter gender: (F/M)";
		cin >> gen_choice;
		gen_choice= toupper(gen_choice);
	}

	int * index_ptr = 0;
	int * temp_index_ptr = 0;

	for (int i=0; i<size; i++)
	{
		if (gen_choice == gen[i] )
		{
			index_ptr = new int[i+1];
			temp_index_ptr = new int[i+1];

			for (int j=0; j<i; j++)
				temp_index_ptr[j] = index_ptr[j];

			temp_index_ptr[i] = i;
			
			delete [] index_ptr;

			index_ptr = temp_index_ptr;
			
		}

	}
	return index_ptr;
}
Last edited on
You have 2 choices. You can create a new list with all the values found that match your search, or you can print as you search (each time you find one, you print it). The new list could be a list of pointers or indices to the data instead of a copy of the data, to save space.

You can only return ONE thing from a function once. That is, as soon as you call return, the function ends, and it can only return one thing at that point (that one thing could be a list, though). A different function format with reference parameters can return multiple things, but that does not work for this type of problem (but if you wanted to create a list of all males and another list of all females it could return both lists that way).

that would look like

void getlists(input, type *femalelist, type*malelist); //pointers are by reference
Topic archived. No new replies allowed.