const pointer function and pass by reference



I am having trouble allocating a new array , this is my old function it worked perfectly but now I need to change it to a const function for my HW assignment. I am not asking for you to do the assignment for me, i have the rest of the program completed just struggling with this function

any tips or suggestions appreciated

old 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
StudentType* SortStudentsByName(StudentType* student, int numStudents)
{
   int startScan,
   minIndex;

   for (startScan = 0; startScan < (numStudents-1); startScan++) 
   {
      minIndex = startScan;
      for ( int index = startScan; index < numStudents; index++) 
      {
         if( student[index].studentName < student[minIndex].studentName)
            minIndex = index;
      }

       if(minIndex!=startScan)
       {
           StudentType temp = student[minIndex]; 
           student[minIndex] = student[startScan];
           student[startScan] = temp;
       }
   }

   cout << endl;
   cout << "List of Students sorted Alphabetically "<< endl;
   DisplayAllStudents(student, numStudents);
   return student;
}



I think it has to do with the three line I commented out, this is my code:
New 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
StudentType* SortStudentsByName(const StudentType* student, int numStudents)    
{
   StudentType* New_StudentType;

   //Allocate a new array
   New_StudentType = new StudentType[numStudents];

   int startScan,
   minIndex;

   for (startScan = 0; startScan < (numStudents); startScan++)
   {
       minIndex = startScan;
       for ( int index = startScan; index < numStudents; index++)
       {
          if( student[index].studentName < student[minIndex].studentName)
        minIndex = index;
       }

       New_StudentType = student[minIndex]; //error 1
       student[minIndex] = student[startScan];// error 2
       student[startScan] =  New_StudentType;// error 3
   }
   cout << endl;
   cout << "List of Students sorted Alphabetically "<< endl;
   DisplayAllStudents(student, numStudents);
   return New_StudentType; 
}
Actually you are trying to update the passed list (by swapping), and for const you can not do so.
If you require to modify the list then remove const or create a temporary copy of list in function for swapping and display in itself.
First: copy the content of student to New_StudentType which will be the sorted list.
Then: within the loope on line 11 of your New code everything is done for New_StudentType and not student.
Topic archived. No new replies allowed.