正在分配一个数组C++
Allocating an array C++
我在分配新数组时遇到问题,这是我的旧函数,它运行得很好,现在我正试图将其更改为常量
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;
}
我认为这与我评论的三行有关,这是我的代码:
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;
}
在您的新函数中,您有一个参数:
const StudentType* student
在这种情况下,const可以在类型的任一侧,因此这相当于
StudentType const* student
因此CCD_ 1是指向CCD_。接下来要注意的是,有两种方法可以声明const指针:一种防止您更改指向的WHAT,另一种防止更改指向的DATA
因此,在您的情况下,您可以更改指针值,但不能使用此指针更改数据。
继续,您列出的第一个错误是:
New_StudentType = student[minIndex]; //error 1
这是错误的,因为您试图将minIndex
处的student
数据分配给指针New_StudentType,这些是不兼容的类型。
您标记的下一个错误是:
student[minIndex] = student[startScan];// error 2
如上所述,您可以更改指针值,但不能更改学生数据,您正试图使用此语句更改数据。
错误3有相同的问题:
student[startScan] = New_StudentType;// error 3