Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The variable declared in for-loop of c++ is not initialised

#include <iostream>
#include <Windows.h>

void selection_sort(int*,int);
void output_array(int*, int);

int main() {
    using namespace std;
    int numbers[] = { 4, 6, 8, 2, 7, 5, 0,1, 3, 9 };
    int length = 10;

    selection_sort(numbers, length);
    output_array(numbers, length);

    Sleep(10000);
    return 0;
}

void output_array(int* start, int length) {
    for (int i = 0; i < length; i++) {
        std::cout << *(start + i) << " ";
    }
    std::cout << std::endl;
}

void selection_sort(int* start, int length) {
    for (int i = 0; i < length; i++) {
        int max = *start;
        int max_i = 0;
        for (int j = 1; j < (length - i); j++) {
            //find out the maximum
            if (max < *(start + j)) {
                max = *(start + j);
                max_i = j;
            }
        }
        //put it at the end
        for (int k = max_i; k < (length - i -1); k++) { //The problem is HERE
            *(start + k) = *(start + k + 1);
        }
        *(start + length - i) = max;
    }
}

Perhaps it is a problem simple enough, but why when it comes to the last for loop, k is undefined? Is it because max_i is not a compile-time constant?
Variables
Program at this step
This doesn’t make sense to me.

When it comes to the second largest number, k behaves as expected.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

void selection_sort(int* start, int length) {
    for (int i = 0; i < length; i++) {
        int max = *start;
        int max_i = 0;
        for (int j = 1; j < (length - i); j++) {
            //find out the maximum
            if (max < *(start + j)) {
                max = *(start + j);
                max_i = j;
            }
        }
        //put it at the end
        for (int k = max_i; k < (length - i -1); k++) {
            *(start + k) = *(start + k + 1);
        }
        // The problem was here, you wanted to access memory that does not belong to you.
        *(start + length - i - 1) = max;
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading