#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
srand(time(NULL));
int sizer = (rand() % 15) + 2;
int nenad[sizer];
for (int i = 0; i < sizer;i++)
nenad[i] = (rand() % 15) + 1;
for (int i = 0; i < sizer;i++)
cout << nenad[i] << endl;
for (int i = 0; i < sizer;i++)
{
for (int j = i + 1;i < sizer;j++)
{
if (nenad[i] > nenad[j])
{
int temp = nenad[i];
nenad[i] = nenad[j];
nenad[j] = temp;
}
}
}
cout << "The biggest elements are : " << nenad[sizer-1] << " and " << nenad[sizer-2] << endl;
程序将随机数随机数添加到数组中。虽然他们被淘汰了,但程序崩溃了。为什么呢?
答案 0 :(得分:9)
你的循环结束条件似乎很奇怪,我推测
for (int j = i + 1;i < sizer;j++)
应该是
for (int j = i + 1;j < sizer;j++)
答案 1 :(得分:3)
你的循环条件也被打破了。应该比较j&lt;分级机。
for (int i = 0; i < sizer;i++)
{
// we don't check j here
for (int j = i + 1;i < sizer;j++)
{
//j can exceed the size of nenad and read from a bad address
if (nenad[i] > nenad[j])
{
int temp = nenad[i];
// same as above
nenad[i] = nenad[j];
// or write to a bad address
nenad[j] = temp;
}
}
}
你应该真正考虑使用/做的另一件事是使用 valgrind 。当我们的眼睛不能时,它会为你捕捉到它。