1. What are wrong in the following code? Please point out.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
voidmain() { char a = 'a'; int b = 0; int *pInt1 = &b; int c = *pInt1; pInt1 = (int*)(&a); int *pInt2 = pInt1 + 1; int d = *pInt2; void *pV = &a; // char * pV = &a; pV++; // 对空指针不能最算术运算 char e = *pV; }
2. What are wrong in the following code? Please provide your FIX.
Common.h
1 2 3 4 5
int var1; voidfoo(int input) { // some code }
TestA.h
1 2 3 4 5 6 7 8
#include"Common.h" #include"TestB.h"
classCTestA { private: CTestB m_b; };
TestB.h
1 2 3 4 5 6 7 8
#include"Common.h" #include"TestA.h"
classCTestB { private: CTestA m_a; };
TestA.cpp
1 2
#include"TestA.h" // some code
TestB.cpp
1 2
#include"TestB.h" // some code
提前声明,结构体内部都采用指针而不是实体。
C. STL
1. Errors, inefficiency and potential bugs exsit in the following code, please point them out.
intfoo(std::map<int, int>& mapIn, std::set<int>& setIn) { std::vector<int> va(10); std::vector<int> vb; std::copy(va.begin(), va.end(), vb.begin()); //std::vector<int> vb(va); std::vector<int> vc(100); auto iter = va.begin() + 5; int varInt = *iter; va.push_back(vc.begin(), vc.end()); varInt = *(++iter); if (mapIn[4] == 0) { // do something } auto itVec = std::find(vc.begin(), vc.end(), 100); if (itVec != vc.end()) { // do something } //auto itSet = setIn.find(10); //Set本来就是有序的结构,利用可以进行二分查找,效率更高 auto itSet = std::find(setIn.begin(), setIn.end(), 10); if (itSet == setIn.end()) { // do something } }
2. Please see the following code, TypeA could be either a function pointer or a functor, please try to provide the definition for TypeA in both function pointer way and functor way.
1 2 3 4 5 6
voidfoo(TypeA processor) { int paraInt = 0; constchar* pParaStr = "Test"; int rtn = processor(paraInt, pParaStr); }