cs31s08finalsol

cs31s08finalsol - UCLA Computer Science 31 Spring 2008...

Info iconThis preview shows pages 1–4. Sign up to view the full content.

View Full Document Right Arrow Icon
UCLA Computer Science 31 Spring 2008 Final Review Problems 1. Fill in the line appropriately to complete the cute function, such that it outputs “cute” on the screen. The line of code you write must not have any brackets. void cute(char* str, char* &ptr) { ptr = new char[5]; *ptr = str[0]; str += 4; ptr[1] = *str; ptr += 2; ptr[1] = *(str+2); *ptr = *(str+1); ptr += 2; ptr[0] = '\0'; ptr -= 4; } int main() { char* set = "computer"; char* s; cute(set, s); cout << s << endl; delete[] s; return 0; }
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
2. Design the class named “Goldfish.” Class Goldfish { public: Goldfish(int capacity); ~Goldfish(); void remember(char c); void forget(); void printMemory() const; // prints the content of m_memory private: char* m_memory; int m_amount; int m_capacity; }; (a) Define the constructor. Dynamically allocate capacity ‐many characters to m_memory . Initialize m_memory with dot(‘.’)s. If capacity is not positive, then set it to 3 by default. Goldfish::Goldfish(int capacity) { if(capacity < 1) m_capacity = 3; else m_capacity = capacity; // record the capacity m_memory = new char[m_capacity]; // allocate memory m_amount = 0; // initialize the amount // of memory used } (b) Implement remember . Store the character into m_memory . If the m_capacity is exceeded, then discard the oldest character from m_memory to open up a free slot. (This is an example of LRU (Least Recently Used) replacement.) void Goldfish::remember(char c) { if(m_amount == m_capacity) { for(int i=0 ; i < m_capacity-1 ; i++) m_memory[i] = m_memory[i+1]; m_amount--; } m_memory[m_amount] = c; m_amount++; }
Background image of page 2
(c) Implement forget . Clear memory by filling dot(‘.’)s into memory . void Goldfish::forget() { for(int i=0 ; i < m_amount ; i++) m_memory[i] = ‘.’; m_amount = 0; } (d) Implement the destructor. Goldfish::~Goldfish()
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 4
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 9

cs31s08finalsol - UCLA Computer Science 31 Spring 2008...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online