Class Notes (837,548)
Canada (510,312)
CMPT 225 (60)
John Edgar (28)
Lecture

CMPT 225 Week 1 Lecture 3

3 Pages
130 Views
Unlock Document

Department
Computing Science
Course
CMPT 225
Professor
John Edgar
Semester
Summer

Description
void MyStack::push(float elem) { // if arr is full, create a new array if (top == n) { float* old = arr; // pointer to old array, in auto storage, but lifetime is only that of if n = n * 2; arr = new float[n]; // copy contents over from old array for (int i = 0; i < n/2; i++) { arr[i] = old[i]; } // however, old array is still sitting in free store! Only pointer to it was destroyed. // basically containing undo record in stack. Eventually will run out of dynamic memory. Crash, hopefully just program and not CMPT. // Have a memory leak (dun dun dun) (no auto garbage collection) delete [] old; // deallocates memory. [] only required if it's an array. // auto garbage collection has cost, because we don't know when it's going to happen //Takes processing seconds. May be important, or not important, depending on program. } arr[top] = elem; top++; } Dynamic memory: The heap or the free store float MyStack::peek() { return arr[top - 1]; // top is always next thing to insert } Did basic test first, now finishing pop: // PRE: stack is non-empty use namespace std void pushTest(); void popTest(); int main() { pushTest(); popTest(); cout << endl << endl; return 0; } void pushTest() { MyStack st; st.push(2.4); cout << st.peek() << endl; st.push(5.7); cout << st.peek() << endl; st.push(13.1); cout << st.peek() << endl; } void popTest() { MyStack st; st.push(2.4);
More Less

Related notes for CMPT 225

Log In


OR

Join OneClass

Access over 10 million pages of study
documents for 1.3 million courses.

Sign up

Join to view


OR

By registering, I agree to the Terms and Privacy Policies
Already have an account?
Just a few more details

So we can recommend you notes for your school.

Reset Password

Please enter below the email address you registered with and we will send you a link to reset your password.

Add your courses

Get notes from the top students in your class.


Submit