C++代码中断行,为了我的爱,我无法修复它

C++ code breaks into line and for the love of me I can't fix it

本文关键字:中断 代码 C++ 我的爱      更新时间:2023-10-16

基本上,我的代码应该接受用户关于马拉松选手的输入,然后显示3个最佳时间,并能够搜索和显示任何选手。现在,代码仍然很简单,但它至少应该接受输入,按升序组织信息(winners函数),当我决定编译代码进行测试时,我正在编写显示函数,然后一切都会顺利进行。基本上,当我必须输入第一个跑步者的名字时,代码会分解成这一行:

static void __CLRCALL_OR_CDECL assign(_Elem& _Left, const _Elem& _Right) _NOEXCEPT
{   // assign an element
    _Left = _Right;
}

首先,我不知道这意味着什么,也不知道为什么左=右,其次,一个朋友在他的机器上运行了我的代码,并告诉我他没有遇到任何错误。

这是我的代码:

#include <iomanip>
#include <iostream>
#include <math.h>
#include <string>
using namespace std;
#pragma once
#include <string>
using namespace std;
class race
{
private:
public:
    int timeH, timeM, timeS, timeT;
    int number;
    string name;
    void input();
};
int size;
race *runner = new race[size];
void input();
void winners();
void display();
int main(){

    input();
    winners();
    display();
    system("pause");
}
void input(){
    cout << "Indique la cantidad de corredores: ";
    cin >> size;
    for (int i = 0; i < size; i++){
        cout << "Nombre del corredor ";
        cin >> runner[i].name;
        cout << "Numero del corredor # "<<i;
        cin >> runner[i].number;
        cout << "Tiempo del corredor # " << i << endl << "Indique cuantas horas tardo :";
        cin >> runner[i].timeH;
        runner[i].timeH = runner[i].timeH * 3600;
        cout << "Cuantos minutos: ";
        cin >> runner[i].timeM;
        runner[i].timeM = runner[i].timeM * 60;
        cout << "Cuantos segundos: ";
        cin >> runner[i].timeS;
        runner[i].timeT = runner[i].timeH + runner[i].timeM + runner[i].timeS;
    }
}
void winners(){
    race temp;
    int flag = 1;
    for (int j = 1; (j <= size) && flag; j++){
        flag = 0;
        for (int i = 0; i < size-1; i++){
            if (runner[i + 1].timeT < runner[i].timeT)
            {
                temp = runner[i];
                runner[i] = runner[i + 1];
                runner[i + 1] = temp;

                flag = 1;
            }
        }
    }
}

提前感谢,如有帮助,不胜感激。

int size;
race *runner = new race[size];

这就是一个问题。您正在分配内存,但尚未设置size(该分配在调用main()之前运行)。这意味着您正在执行new race[0](因为size被初始化为零,因为它是全局int)。呃,程序的其余部分正在调用未定义的行为,因为runner是一个空数组,您正试图(非法)访问它。

您也在泄漏内存,因为您从未delete []使用new []分配的内存。我建议听从约阿希姆的建议,使用std::vector

问题是:

int size;
race *runner = new race[size];

未初始化的全局变量被初始化为,因此size将被初始化为零,因此您正在分配一个零大小的数组,这意味着对数组的任何访问都将越界,并导致未定义的行为

有两种方法可以解决这个问题:

  1. 等待分配,直到您知道大小。(不是我推荐的解决方案。)

  2. 使用std::vector,它是一种动态大小的"数组"类型(我确实建议使用该解决方案)。