一个常见的错误时编写代码

实验室阶段做练习,其中,变化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;
}


版权声明:本文博主原创文章,博客,未经同意不得转载。

posted @ 2015-10-10 20:56  phlsheji  阅读(213)  评论(0编辑  收藏  举报