コードを書くときによくあるエラー
実験室には段階的な練習問題があります.その中にバグを直す問題があります.
この問題はいくつかの試験点を受けた.
1配列ポインタを最初に申請するときは、配列内の各メンバーを初期化することを忘れないでください.
2ポインタドメインポインタ間の割り当てと参照
3=と==の違い
4メモリリーク:リリースポインタとリリースポインタのポインタ
5このmigic number
次のように変更します.
#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; ksize(); 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; ksize(); 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 *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;
}