Jestem początkującym c ++ i mam problem ze zrozumieniem następującego kodu.
#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;
}
Kod działa dobrze, ale nie rozumiem, dlaczego muszę zadeklarować funkcję struct student * maximumScorer (student **, int); z ** tj. podwójnym wskaźnikiem, gdy wskaźnik przechodzący jest właśnie zainicjowany jednym.
Zadeklarowałbym funkcję tylko jednym *, ponieważ jest to typ zmiennej, którą chciałbym przekazać?
Dziękuję Ci bardzo.
Odpowiedzi:
0 dla odpowiedzi № 1Ponieważ stud
zmienna w main
jest tablicą student
wskazówki. Kiedy przekazujesz tablicę za pomocą argumentu, potrzebujesz wskaźnika do pierwszego elementu, bez względu na elementy. Ponieważ tablica jest tablicą wskaźników, masz wskaźnik do wskaźnika.