C++代码中断行,为了我的爱,我无法修复它
C++ code breaks into line and for the love of me I can't fix it
基本上,我的代码应该接受用户关于马拉松选手的输入,然后显示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
将被初始化为零,因此您正在分配一个零大小的数组,这意味着对数组的任何访问都将越界,并导致未定义的行为。
有两种方法可以解决这个问题:
等待分配,直到您知道大小。(不是我推荐的解决方案。)
使用
std::vector
,它是一种动态大小的"数组"类型(我确实建议使用该解决方案)。
相关文章:
- 我的代码运行良好,但在游戏循环中中断
- 使用个人C++库编译代码时,与头文件一起使用时会中断
- 中断长代码 snprintf 格式和参数
- 为什么我的代码在第一个 if 语句处中断?
- 如何在不中断剩余代码的情况下仅C++中输入整数
- 移动返回对象的构造函数会中断C++98 代码?
- 为什么使用复制构造函数会导致此代码中断?
- VS2015 中的方法存在检查器代码中断
- 递归期间代码执行中断
- 添加<iostream>会中断 G++-7 中的代码
- 为什么Visual Studio Release生成在未执行的代码行中断
- 中断代码执行
- 如何中断本机扩展代码而不杀死解释器
- 在WNDClasSex中断代码中将代码添加到WNDPROC回调中
- C++代码中断行,为了我的爱,我无法修复它
- 为什么代码在代码块中的断点处没有中断
- 尝试分配值时C++继承中断的代码
- 编译器优化会中断代码
- GCC优化标志中断代码
- 我可以在不中断代码的情况下删除此警告吗?