所以老实说我不能告诉你这是怎么回事。我读过有类似问题的线程,但人们正在处理内存和其他东西的分配,到目前为止,这超出了我作为程序员的范围,而我的程序几乎没有做过这么复杂的事情。
int main() {
double input[5] = { 5.0, 6.0, 8.0, 4.3, 5.6 };
GradeBook test(sizeof(input), input);
test.bubbleSort();
test.printAll();
return 0;
};这些是我的私人数据成员
const static int gradeBookSize = 6;
int classSize;
double grades[gradeBookSize];
bool insertionSorted = false; //simply for efficency
bool bubbleSorted = false;构造函数为我的GradeBook类
GradeBook(int inputSize, double inputGrades[]) {
classSize = inputSize;
for (int i = 0; i < classSize; i++) {
grades[i] = (inputGrades[i]);
}
for (int i = classSize; i < sizeof(grades); i++) {
grades[i] = 0;
}
}最后,我在main()方法中实际使用了两个方法
void bubbleSort() {
//sorts grades in descending order using bubblesort algorithm
bool sorted = false;
while (!sorted) {
for (int i = 0; i < (sizeof(grades) - 1); i++) {
if (grades[i] < grades[i + 1]) {
double tmp = grades[i + 1];
grades[i + 1] = grades[i];
grades[i] = tmp;
}
}
bool test = false;
for (int i = 0; i < sizeof(grades) - 1; i++) {
if (grades[i] < grades[i + 1]) test = true;
}
sorted = !test;
}
bubbleSorted = true;
insertionSorted = false;
}
void printAll() {
for (int i = 0; i < sizeof(grades); i++) {
cout << grades[i] << "\t";
}
cout << endl;
}在这里,我们有我的调试输出,我不能这样做的正面或反面。
The thread 0x3378 has exited with code 0 (0x0).
Unhandled exception at 0x0130FC38 in CS260_Project4_James_Casimir.exe:0xC00001A5: An invalid exception handler routine has been detected (parameters: 0x00000003).
CS260_Project4_James_Casimir.exe has triggered a breakpoint.
Run-Time Check Failure #2 - Stack around the variable 'test' was corrupted.
Unhandled exception at 0x00363A09 in CS260_Project4_James_Casimir.exe: Stack cookie instrumentation code detected a stack-based buffer overrun.
Unhandled exception at 0x00363A09 in CS260_Project4_James_Casimir.exe: Stack cookie instrumentation code detected a stack-based buffer overrun.
Unhandled exception at 0x00363A09 in CS260_Project4_James_Casimir.exe: Stack cookie instrumentation code detected a stack-based buffer overrun.
The program '[7400] CS260_Project4_James_Casimir.exe' has exited with code 0 (0x0).发布于 2016-05-01 19:14:30
主要问题是您使用sizeof不正确。sizeof关键字返回类型所包含的字节数(),而不是数组中的项数。
代码中最终发生的情况是,您实际上使用的不是数组中的项目数,而是实际使用的(在grades数组中)
sizeof(double)*6
它很可能是48 (数组中的6个项,每个项是8个字节)。很明显,问题在于循环迭代次数过多,导致数组访问中的内存访问(如您所见,崩溃)。
如果类型是数组,那么使用grades的sizeof数组中的项数将是:
sizeof(grades) / sizeof(grades[0])
这是一个条目占用的字节数除以字节数。
如果您想要比上面更直观的东西,那么使用std::array会给您提供以下信息:
#include <array>
#include <iostream>
std::array<double, 6> grades;
int main()
{
std::cout << grades.size(); // will output 6.
}https://stackoverflow.com/questions/36970691
复制相似问题