0

I'm trying to arrange a random array. In the code it's just the first step of swapping places by size. When running the code a get Debug Error and the output after the swap shows that the first number in the array was deleted and the last is a long random number that was in the memory. It looks like it starts the swapping from i=1, why?

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

void buildArray(int arr[], int size) {
    srand ( (unsigned int)time(NULL) );
    for(int i = 0; i < size; ++i)
        arr[i] = rand() % 50 + 0;
}


void dispArray(int arr[], int size) {
     for(int i = 0; i < size; ++i)
        cout << i << ": " << arr[i] << endl;
}


int main()
{
        const int size = 5;
    int     arr[size];
    buildArray(arr, size);
    dispArray(arr, size);

    int swapHolder = -1;
    for(int i = 0; i < size; ++i) {
    if(arr[i] > arr[i+1]) {
            swapHolder = arr[i+1];
            arr[i+1] = arr[i];
            arr[i] = swapHolder;
            cout << endl;
        }
    }
    dispArray(arr, size);

    return 0;
}  


Output example:
0: 46
1: 15
2: 47
3: 5
4: 19


0: 15
1: 46
2: 5
3: 19
4: -858993460
0

2 Answers 2

2

Here is the problem: if(arr[i] > arr[i+1]), your for loop goes from [0, size - 1], so on the last iteration, lets say size = 5, you would be testing if(arr[5] > arr[6]), accessing the uninitialized arr[6], the right way is to make your for loop go from [0, size - 2]:

for(int i = 0; i < size - 1; ++i) ...
Sign up to request clarification or add additional context in comments.

Comments

1
for(int i = 0; i < size; ++i) {
    if(arr[i] > arr[i+1]) {
            swapHolder = arr[i+1];
            arr[i+1] = arr[i];

The last iteration is for i = size -1. Then

 if(arr[i] > arr[i+1])

means accessing array out of range. This is undefined behavior.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.