【发布时间】:2018-11-18 11:53:01
【问题描述】:
#include<iostream>
#include<string>
struct student {
std::string name;
int age;
float marks;
};
student initiateStudent(std::string name, int age, float marks)
{
student s;
s.age = age;
s.marks = marks;
s.name = name;
return s;
}
student* highestScore(student** stud, int total)
{
float temp = (*stud)->marks;
student **counter= new (student*);
*counter = *stud;
for (int i = 0; i < total; i++)
{
// std::cout<<(*stud)->marks;
if (temp < (*stud)->marks)
{
*counter = *stud;
temp = (*stud)->marks;
}
(*stud)++;
}
*stud = *counter;
delete counter;
return *stud;
}
int main()
{
int totalStudents = 1;
std::string name;
int age;
float marks;
std::cin >> totalStudents;
student *stud = new student[totalStudents];
for (int i = 0; i < totalStudents; i++) {
std::cout << "\nEnter Name: ";
std::cin >> name;
std::cout << "\nEnter age: ";
std::cin >> age;
std::cout << "\nEnter Marks: ";
std::cin >> marks;
stud[i] = initiateStudent(name, age, marks);
//std::cout << "\n Name: " << stud[i].name << "\n" << stud[i].marks;
}
student *topper = highestScore(&stud, totalStudents);
//std::cout << "\nPrinting in Main : " << topper->name;
std::cout<<std::endl << topper->name << " is the topper with " << topper->marks << " marks" << std::endl;
delete[] stud;
std::cin.get();
return 0;
}
当我完成为所有学生输入值时弹出的错误: Visual studio error
但是当我在 code::blocks 中运行相同的代码时,它运行流畅并显示输出:
但即使代码块窗口显示错误,idk 是什么问题,任何帮助都会很棒。
【问题讨论】:
-
将错误消息(和示例输入/输出)发布为块格式的文本(如代码),而不仅仅是图像。
-
除其他外,让我感到困惑的风格是为什么你认为你需要动态分配单个指针,而它可能只是在堆栈上......以及为什么,如果它存在的话得分最高的学生,称为
counter。还有更多要点:为什么不直接使用std::vector而不是另一个new?和std::max_element()?和迭代器而不是原始指针?将其标记为c++11很奇怪,但却很少努力使用该版本中包含的出色标准库功能,而是以更危险的方式重新发明它们。 -
创建指针数组有什么原因吗?
struct对象不需要是指针。 -
@cybermonkey 所示程序实际上并没有创建指针数组。在
new student[totalStudents]中创建的唯一数组是student结构的数组。