了解双指针的问题并将其传递给函数
Understanding issues with double pointers and passing them to functions
我是一个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);与**,即一个双指针,当传递指针只是用一个初始化。
我会用一个*声明函数,因为这是我要传递的变量类型?
因为main
中的stud
变量是一个包含student
指针的数组。当你通过参数传递一个数组时,你需要一个指向第一个元素的指针,无论这些元素是什么。因为数组是指针数组,所以有一个指向指针的指针。
相关文章:
- QMetaObject invokeMethod的基于函数指针的语法
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- c++r值引用应用于函数指针
- 模板函数指针和lambda
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 带有类的函数指针
- () 函子后面的括号,而不是函数指针?
- 全局作用域中函数指针的赋值
- 使用"Task"函数指针队列定义作业管理器
- 将成员函数指针作为参数传递给模板方法
- 如何创建对象函数指针C++映射?
- 匹配函数指针作为模板参数?
- 通过函数指针定义类范围之外的方法
- 存储在类中的函数指针
- C++从函数指针数组调用函数
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 整数键映射到头文件中的成员函数指针
- 从类成员函数到类 C 函数指针的转换
- 如何将内联匿名函数分配给C++函数指针
- 将字符缓冲区强制转换为函数指针