实验室阶段做练习,其中,变化bug称号:
*pContainer = ppContainer[RandomNum%vMod]; std::vector *& pContainer = ppContainer[RandomNum%vMod];//指针的引用,要改变指针的值 //if (pContainer = NULL) if (pContainer == NULL)// = 与==的差别 { //pContainer = new std::vector ; pContainer = new std::vector ; } pContainer->push_back(RandomNum); } return ppContainer;} #include#include int main(int, char**){ std::vector ** ppRandomData = distributeRandomInt(100); for (unsigned int i=0; i<1000; i++) { if (ppRandomData[i]) { std::cout << "Elements in [" << i << "] : "; for (unsigned int k=0; k size(); k++) { std::cout << ppRandomData[i]->at(k) << " "; } std::cout << std::endl; } } delete[] ppRandomData; return 0;}std::vector ** distributeRandomInt(int vMod){ assert(vMod > 0); std::vector **ppContainer; ppContainer = new std::vector *[vMod]; srand(0); for (int i=0; i<1000; i++) { int RandomNum = rand(); std::vector *pContainer = ppContainer[RandomNum%vMod]; if (pContainer = NULL) { pContainer = new std::vector ; } pContainer->push_back(RandomNum); } return ppContainer;}
这个题考了几个考点:
1 首先申请数组指针时一定要记得初始化数组中每个成员
2指针域指针之间的赋值与引用
3= 与==的差别
4内存泄露 :释放指针 与释放指针的指针
5 这个migic number
改动例如以下:
#include//add#include #include std::vector ** distributeRandomInt(int vMod);const int Total = 100;int main(int, char**){ std::vector ** ppRandomData = distributeRandomInt(100); //for (unsigned int i=0; i<1000; i++) for (unsigned int i=0; i<100; i++)//100 migic number { if (ppRandomData[i]) { std::cout << "Elements in [" << i << "] : "; for (unsigned int k=0; k size(); k++) { std::cout << ppRandomData[i]->at(k) << " "; } std::cout << std::endl; } } for (int i=0; i<100; ++i) { if (ppRandomData[i] != NULL) delete ppRandomData[i];//释放数组中每一块申请的内存 } delete[] ppRandomData; return 0;}std::vector ** distributeRandomInt(int vMod){ assert(vMod > 0); std::vector **ppContainer; ppContainer = new std::vector *[vMod]; for (int i=0; i
版权声明:本文博主原创文章,博客,未经同意不得转载。