F
F
Fredik4872021-11-17 22:32:56
C++ / C#
Fredik487, 2021-11-17 22:32:56

Sorting the array is not displayed, garbage is climbing from memory, how to fix it? run-time check failure #2 - stack around the variable 'c' was corrupted?

Task
Given two arrays, sorted by height: A [n] and B [m]. Form an array C[n+m], consisting of array elements A and B, sorted in ascending order.
Conclusion:
619558dc632c6647596526.png
Help please.

#include <iostream>
using namespace std;

int main()
{
  const int ArraySize = 5; // оголосили константу для задання розмірності масиву
  const int ArraySizeC = ArraySize*2;

  int A[ArraySize], * pA, i;
  int B[ArraySize], * pB, j;
  int C[ArraySizeC], * pC, k;
  

  // оголосили: Масив A з ArraySize елементів типу int; покажчик  pA,pB  на int; 
  //змінну i,j типу int
  pA = A; pB = B; pC = C; /* вказівнику pA,pB,pC привласнили адрес нульового елементу масиву*/
  for (i = 0; i < ArraySize; i++)
  {
    cout << "Do enter A[" << i << "] element -->";
    cin >> pA[i]; //p[i] - можно замінити на: *(pA+i), *(A+i) або на звичне нам A[i]
  }
  cout << "\n";
  for (j = 0; j < ArraySize; j++)
  {
    cout << "Do enter B[" << j << "] element -->";
    cin >> pB[j]; //p[j] - можно замінити на: *(pB+j), *(B+j) або на звичне нам B[j]
  }

  for (k = ArraySize,i = 0; k < ArraySizeC && i< ArraySize; k++,i++)
  {
    for (j = 0; j < ArraySize; j++)
    {
      pC[j] = pA[j];
       
    }
    pC[k] = pB[i];
  }



  //Вивід масив А
  cout << "\n Array A[]:\n";
  for (i = 0; i < ArraySize; i++)
  {
    cout << "A[" << i << "]:"<< pA[i] << "\n";
  }
  //Вивід масив B
  cout << "\n Array B[]:\n";
  for (i = 0; i < ArraySize; i++)
  {
    cout << "B[" << i << "]:" << pB[i] << "\n";
  }

  //Сортировка бульбашкою(пузырьком) масиву С:
  for (i = 0; i < ArraySizeC; ++i)
  {
    for (j = 0; j < ArraySizeC; j++)
    {
      if (pC[j] > pC[j + 1])
      {
        // Обмін місцями
        int temp = pC[j];
        pC[j] = pC[j + 1];
        pC[j + 1] = temp;
      }
    }
  }


  //Вивід масив С
  cout << "\n Array C[]:\n";
  for (i = 0; i < ArraySizeC; i++)
  {
    cout << "C[" << i << "]:" << pC[i] << "\n";
  }

  return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2021-11-17
@Fredik487

Out of bounds of the array where you sort. It is from this left memory that you get the random value.
Be careful what indexes you are accessing and what value j can take.
And yet, you can not sort the final array, but form it already sorted. This works much faster. It's called the merge procedure .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question