写代码时常见的错误

22 篇文章 0 订阅
实验室有要做阶段练习题了,其中有一道改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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值