实验室有要做阶段练习题了,其中有一道改bug题:
#include <iostream> #include <vector> int main(int, char**) { std::vector<int>** 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<ppRandomData[i]->size(); k++) { std::cout << ppRandomData[i]->at(k) << " "; } std::cout << std::endl; } } delete[] ppRandomData; return 0; } std::vector<int>** distributeRandomInt(int vMod) { assert(vMod > 0); std::vector<int> **ppContainer; ppContainer = new std::vector<int>*[vMod]; srand(0); for (int i=0; i<1000; i++) { int RandomNum = rand(); std::vector<int> *pContainer = ppContainer[RandomNum%vMod]; if (pContainer = NULL) { pContainer = new std::vector<int>; } pContainer->push_back(RandomNum); } return ppContainer; }
这个题考了几个考点:
1 首先申请数组指针时一定要记得初始化数组中每一个成员
2指针域指针之间的赋值与引用
3= 与==的区别
4内存泄露 :释放指针 与释放指针的指针
5 这个migic number
修改如下:
#include <assert.h> //add #include <iostream> #include <vector> std::vector<int>** distributeRandomInt(int vMod); const int Total = 100; int main(int, char**) { std::vector<int>** 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<ppRandomData[i]->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<int>** distributeRandomInt(int vMod) { assert(vMod > 0); std::vector<int> **ppContainer; ppContainer = new std::vector<int>*[vMod]; for (int i=0; i<vMod; ++i)//初始化数组指针 { ppContainer[i] = NULL; } srand(0); for (int i=0; i<1000; i++) { int RandomNum = rand(); //std::vector<int> *pContainer = ppContainer[RandomNum%vMod]; std::vector<int>*& pContainer = ppContainer[RandomNum%vMod];//指针的引用,要改变指针的值 //if (pContainer = NULL) if (pContainer == NULL)// = 与==的区别 { //pContainer = new std::vector<int>; pContainer = new std::vector<int>; } pContainer->push_back(RandomNum); } return ppContainer; }
写代码时常见的错误
时间: 2024-12-22 22:53:21