我是一名c ++初学者,对以下代码有一个理解问题。
#include <iostream>
using namespace std;
struct student {
string name;
int age;
float marks;
};
struct student *initiateStudent(string , int , float );
struct student *highestScorer(student **, int);
int main ( ) {
int totalStudents = 1;
string name;
int age;
float marks;
cin >> totalStudents;
student *stud[totalStudents];
for( int i = 0; i < totalStudents; i++ ) {
cin >> name >> age >> marks;
stud[i] = initiateStudent(name,age,marks);
}
student *topper = highestScorer(stud,totalStudents);
cout << topper->name << " is the topper with " << topper->marks << " marks" << endl;
for (int i = 0; i < totalStudents; ++i)
{
delete stud[i];
}
return 0;
}
struct student *initiateStudent(string name, int age, float marks)
{
student *temp_student;
temp_student = new student;
temp_student->name = name;
temp_student->age = age;
temp_student->marks = marks;
return temp_student;
}
struct student *highestScorer( student **stud, int totalStudents)
{
student *temp_student;
temp_student = new student;
temp_student = stud[0];
for (int i = 1; i < totalStudents; ++i)
{
if (stud[i]->marks > temp_student->marks)
{
temp_student = stud[i];
}
}
return temp_student;
}
代码工作正常,但我不明白为什么我需要声明函数 struct student * highestScorer(student **,int); 用**即双指针传递指针只用一个初始化。
我会用一个*声明函数,因为那是我要传递的变量类型?
非常感谢。
答案 0 :(得分:0)
因为stud
中的main
变量是一个student
指针数组。当您通过参数传递数组时,您需要一个指向第一个元素的指针,无论元素是什么。由于数组是一个指针数组,因此你有一个指向指针的指针。