cs31 lecture 9

Structure implementing the last in first out

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: nition: a stack is a linear data structure, implementing the Last-in-First-Out principle Typical operations: Push Pop Stacks are used in numerous algorithms, and are ubiquitous in computers Handle function calls / memory Recursive algorithms can always be implemented with a stack 6 The StackLib in C++ 7 An algorithm using stacks function outputInBinary(Integer n) Stack s = new Stack while n > 0 do Integer bit = n modulo 2 s.push(bit) if s is full then return error end if n = floor(n / 2) end while while s is not empty do output(s.pop()) end while end function 8 Dynamic allocation of arrays in C Dynamic allocation: allocate data on the heap (persistent across functions) Static allocation: allocate data on the stack (destroyed at the end of a function) In C, use specific functions to allocate/deallocate data on the heap void* malloc(size_t size); void free(void* ptr); void* realloc(void* ptr, size_t size); 9 A word on pointers A pointer is a variable storing an address in memory address != data (see the reference exemple) An address is a number, possibly very large (fits 64 bits) Be careful: A reference is linked to an existing variable An address can be any number, explicit (eg, 0x12345) or stored in a variable Pointers exist in C and in C++ 10 More on pointers A type “pointer to something” is noted with the symbol * Example: int* a; // a is a pointer to int Special type: void* (a pointer to anything) Property: all pointers are addresses, so they have technically the same storage The address of something is noted with the symbol & next to the varia...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online