2016-09-26 14 views
0

私は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; 
} 

コードが正常に動作しますが、私は機能構造体の学生* highestScorer(学生**、int)を宣言する必要がある理由私は理解していません。 **の場合、つまり、渡すポインタが1で初期化されたときにダブルポインタが使用されます。

私は渡すことになる変数の型であるため、関数を*と宣言していたでしょうか?

ありがとうございました。

+4

私はあなたが良い初心者のC + +の本を停止して読む必要があると思います。これらのポインタとメモリリークはすべて必要ありません。 – juanchopanza

+0

'stud'は' student * 'ではなく、' student * 'の配列です。 (これは、C++の割り当てとI/Oのトッピングを伴うCコードのようです。[Here](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)は良いC++の本の選択) – molbdnilo

+1

'std :: vector 'を使うと、多くの問題を解決できると思います。 –

答えて

0

mainstud変数がstudentポインタの配列であるためです。引数で配列を渡すときは、要素が何であれ、最初の要素へのポインタが必要です。配列はポインタの配列なので、ポインタへのポインタがあります。

+1

このコードにはもっと多くの問題があります。 –

+0

おそらく。しかしそれは別の質問です。 – vz0

関連する問題