I am working on a bit of code that includes arrays in and out of functions, but my programs insist on some very strange behavior that persists regardless of my many efforts to fix the problem. Pseudocode:
main
function randomArray //generates array of random numbers
function printArray //prints the array to console
function sortArray //sorts the array lowest -> highest
function printArray
end
The problem is that the second time the printArray function is run,after sorting the array, the numbers printed to console are all very strange.
Output example:
41 85 72 38 80 69 65 68 96 22 49 67 51 61 63 87 66 24 80 83
22 0 1 0 0 0 20987800 20987808 20987808 512 0 0 19921228 19921520 20921280 -1 19921360 20779373 20987800 20922800
The number 22 at the start suggests that it somehow got the first number right, but after that I see no connection at all.
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
#include <iostream>
int randomWithLimits(int lower, int upper){
int diff = upper - lower + 1;
return std::rand() % diff + lower;
}
void printArray(int *array, int array_length){
for(int i = 0; i < array_length; i++){
std::cout << array[i] << " ";
}
std::cout << std::endl;
}
int* randomizeArray(int *array, int array_length){
for(int i = 0; i < array_length; i++){
int rnum = randomWithLimits(0, 100);
array[i] = rnum;
}
return array;
}
int* sortArray(int *array, int array_length){
int sorted[20] = {};
for(int i = 0; i < array_length; i++){
int lowest = i;
for(int j = 0; j < array_length; j++){
if(array[j] < array[lowest]){
lowest = j;
}
}
sorted[i] = array[lowest];
array[lowest] = 1000;
}
array = sorted;
return array;
}
int main() {
int empty[20] { };
int *array = randomizeArray(empty, 20);
printArray(array, 20);
array = sortArray(array, 20);
printArray(array, 20);
return 0;
}
|
Can anyone explain this very strange behaviour, or what can be done to fix it? Any help is greatly appreciated. Apologies for the vague/indirect question.