【发布时间】:2016-05-01 18:58:54
【问题描述】:
老实说,我不能告诉你这有什么问题。我读过有类似问题的线程,但是人们正在处理内存和事物的分配,到目前为止,这超出了我作为程序员的范围,而且我的程序几乎没有做任何复杂的事情。
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(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).
【问题讨论】:
-
sizeof(grades)-- 你认为这会是什么?它不会是你期望的那样。事实上,无论你在哪里使用它都会错误地使用它,比如sizeof(input)。 -
@PaulMcKenzie 我认为它类似于 java 的 .size() 函数。到底是什么搞砸了这一切?
-
sizeof(T)返回类型T所包含的字节 数,而不是数组中的项目数。 C++ 不是 Java——不要试图通过使用 Java 作为模型来弄清楚 C++。 -
@paulMckenzie 在这种情况下我应该使用什么来查找数组的大小?
-
数组是愚蠢的,因为它们对自己的大小一无所知。如果你想拥有类似 Java 的东西,你会使用
std::array<double, 5>,它确实有一个size()成员函数。
标签: c++