You both have a point about the separate function... I will code the algorithm in a separate function and call it within main. So, as both of you are saying, I am to deallocate the memory of the array at the end of the program, right before it returns 0... To prevent memory leaks. I don't fully understand why there would potentially be a memory leak when the program deletes it upon exit, right?
EDIT: WOW. I was so close looking at it now... My algorithm that I had originally written for my sorting was:
1 2 3
|
temp1 = arr[i];
arr[i] = arr[i - 1];
arr[i - 1] = temp1;
|
All I needed to do was put this in a separate function, create a variable 'j', and decrement it so that the loop continues??? The frustration is real.
Also, I appreciate the help a lot. You've made me realize how much easier this was than what I was doing... I created too many variables and the actual program requires much less lines of code than expected. Thanks guys!
I have another program that I coded last week and was wondering if you guys would be willing to help me with it as well. The issue that I'm having with this one is that it randomly triggers breakpoints after '-1' is entered, or even sometimes when just inputting values into array indexes.
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
|
//Objective: Create an array of numbers based upon user input.
//
// Program logic :
// Ask the user for how big to initially size the array. CHECK
// Create an array based upon that size. CHECK
// Ask for a number, insert that number into the next unused place in the array. CHECK
// Repeat inserting and resizing the array as needed or until they enter -1 for the number. CHECK
// Print the list. CHECK
#include <iostream>
using namespace std;
int main() {
int size, num = 0, inc = 0;
int *arr;
cout << "Please enter your desired array size: " << endl;
cin >> size;
arr = new int[size];
cout << "Please enter your array index values: " << endl;
while (num != -1) {
cin >> num;
if (num == -1) {
int x = 0;
for (x; x < inc; x++) {
cout << "The value stored at index " << x << " is: " << arr[x] << endl;
}
}
else {
arr[inc] = num;
inc++;
if (inc == size) {
size += size;
cout << "The size of your array is now: " << size << endl;
}
}
}
delete[] arr;
system("pause");
return 0;
}
|