R
R
rEAcT1oNmanT1s2014-06-03 20:46:19
C++ / C#
rEAcT1oNmanT1s, 2014-06-03 20:46:19

How to solve this kind of error in C++?

Good day, Khabrovchani and not only :)
I wrote a simple bubble sorting program. Very simple.
Instead of the usual sorted numbers, it shows a negative number, like: -842150451 (in all cells of the array)
5ff1ab80225b47a0a1c04823522961ba.png

#include <iostream>
#include <conio.h>

using namespace std;

int main()
{
  setlocale(LC_ALL, "Russian");
  cout << "\t\t***Сортировка пузырьком***\n\n";

  int m;

  cout << "Введите кол-во массивов: ";
  cin >> m;

  int *D = new int [m];

  cout << "Заполните весь массив:\n";

  for (int i = 0; i < m; i++)
  {
    cout << "D[" << i << "] = ";
    while (!(cin >> D[m]))
    {
      cin.clear();
      while (cin.get() != '\n');
      cout << "D[" << i << "] = ";
    }
  }

  for (int i = 0; i < m; i++)
  {
      for (int j = m - 1; j > i; j--)
      {
        if (D[j] < D[j - 1])
        {
          swap(D[j], D[j - 1]);
        }
      }
  }
  
  for (int i = 0; i < m; i++)
  {
      cout << "D[" << i << "] = " << D[i] << endl;
  }
  cout << "Массив рассортирован!!!\n";

  _getch();
  return 0;
}

I will be grateful for the hint!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
drozdVadym, 2014-06-03
@rEAcT1oNmanT1s

Replace
the line with
And yes, as noted above, it’s better not
PS
And usually such values ​​​​when output or in debugging can mean that you are reading an uninitialized memory area.

R
Rsa97, 2014-06-03
@Rsa97

The best way to find a bug is to start debugging step by step and see how the values ​​of the variables change at each step. Most likely, the array is initially filled incorrectly.
PS And yet, the "number of arrays" in your program is always 1. Only the size (number of elements) of the array changes.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question