C/C++ Interview Exam (阮泓璋 Jerry Juan) ================================= 1. Where in memory are the variables stored? * Global variables * Static variables * Constant data types * Local variables (declared and defined in functions) * Variables declared in *main* function * Dynamically allocated space ``` Please answer here... * Global variables : stack * static variable : * Constant data types : * Local variables : stack * Variables declared in *main* function : stack * Dynamically allocated space : Heap * ``` 2. Are the following legal or illegal uses of const pointers? Which lines are illegal ones? What are the benefits of using const? ~~~c // Question 2 const char *str = "hello"; char c = *str; str++; *str = 'a'; str[1] = 'b'; ~~~ `` Please answer here... str++ is illegal const str can not modify. ``` 3. What is the output of the following program? ~~~c++ // Question 3 #include <iostream> class A { public: A(int n = 0) : m_n(n) { std::cout << 'd'; } A(const A& a) : m_n(a.m_n) { std::cout << 'c'; } private: int m_n; }; void f(const A &a1, const A &a2 = A()) { } int main() { A a(2), b; const A c(a), &d = c, e = b; b = d; A *p = new A(c), *q = &a; static_cast<void>(q); delete p; f(3); std::cout << std::endl; return 0; } ~~~ ``` Please answer here... dccdxcxx ``` 4. Please write a function to shuffle a vector of integers. ~~~c++ // Question 4 #include <vector> #include <stdexcept> #include <iostream> class Shuffler { public: static void shuffle(std::vector<int>& sequence) { // TODO: Waiting to be implemented //get system time for shffule condition if(sequence.size() == 0) return; system time = GetSystemTime(); int nChangePos = time.second%sequence.size(); int nCurEleVal , nNewElePos; for(int i=0 ; i < sequence.size() ; i++) { nNewElePos = (i + nChangePos)%sequence.size(); nCurEleVal = sequence[nNewElePos]; sequence[nNewElePos] = sequence[i]; sequence[i] = nCurEleVal; } } }; #ifndef RunTests int main() { std::vector<int> v = { 1, 2, 3, 4, 5, 6 }; Shuffler::shuffle(v); return 0; } #endif ~~~ 5. The following code is for inserting an element at the front of a list. Please correct it if you find anything inappropriate, and describe what you find. ~~~c++ struct IntElement { int data; IntElement *next; }; bool insertInFront (IntElement *head, int data) { IntElement *newElem = new IntElement; if (!newElem) return false; newElem->data; head = newElem; return true; } ~~~ ``` Please describe what you find here ... //insert this line to set the next element newElem->next = head; //re-position the link list's first element head = newElem; ``` ~~~c++ // Please write the correct code here... bool insertInFront (IntElement *head, int data) { IntElement *newElem = new IntElement; if (!newElem) return false; newElem->data; newElem->next = head; head = newElem; return true; } ~~~