【问题标题】:Error in the code,when running in visual studio 2017 and not in codeblocks代码错误,在 Visual Studio 2017 中运行而不是在代码块中
【发布时间】: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 中运行相同的代码时,它运行流畅并显示输出:

same code on codeblocks

但即使代码块窗口显示错误,idk 是什么问题,任何帮助都会很棒。

【问题讨论】:

  • 将错误消息(和示例输入/输出)发布为块格式的文本(如代码),而不仅仅是图像。
  • 除其他外,让我感到困惑的风格是为什么你认为你需要动态分配单个指针,而它可能只是在堆栈上......以及为什么,如果它存在的话得分最高的学生,称为counter。还有更多要点:为什么不直接使用std::vector 而不是另一个new?和std::max_element()?和迭代器而不是原始指针?将其标记为 c++11 很奇怪,但却很少努力使用该版本中包含的出色标准库功能,而是以更危险的方式重新发明它们。
  • 创建指针数组有什么原因吗? struct 对象不需要是指针。
  • @cybermonkey 所示程序实际上并没有创建指针数组。在new student[totalStudents] 中创建的唯一数组是student 结构的数组。

标签: c++ c++11 pointers


【解决方案1】:

highestScore 具有修改main 中的stud 的副作用,使其不再指向分配有new 的块,而是位于该块中间的某个位置。然后delete[] stud 表现出未定义的行为。

highestScorestudent*,并删除内部各处的额外间接级别。更好的是,始终使用std::vector&lt;student&gt;,并避免手动管理内存。

【讨论】:

    猜你喜欢
    • 2021-08-21
    • 2019-08-17
    • 2022-09-23
    • 1970-01-01
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多