0

I'm a c++ beginner and have an understanding issue with the following code.

#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;
}

The code works fine, but I don't understand why I need to declare the function struct student *highestScorer(student **, int); with ** i.e. a double pointer when the passing pointer is just initialized with one.

I would have declared the function just with one * since that is the type of variable I would be passing?

Thank you very much.

AT90
  • 25
  • 3
  • 4
    I think you need to stop and read a good introductory C++ book. There is no need for all these pointers and memory leaks. – juanchopanza Sep 26 '16 at 07:51
  • `stud` is not a `student*`, it's an array of `student*`. (This looks like C code with a topping of C++ allocation and I/O. [Here](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) is a good selection of C++ books.) – molbdnilo Sep 26 '16 at 07:57
  • 1
    I think using an `std::vector` would solve a lot of your problems. – Bo Persson Sep 26 '16 at 07:59

1 Answers1

0

Because the stud variable in main is an array of student pointers. When you pass an array by argument you need a pointer to the first element, whatever the elements are. Since the array is an array of pointers, you have a pointer to a pointer.

vz0
  • 32,345
  • 7
  • 44
  • 77