Dynamic Pointer and Dynamic Memory Allocation in C++

Days ago a mate asked me a favor in his code and I got trouble in dynamic pointer and dynamic memory allocation.
Well, one-dimensional pointer is easy to use, and you can easily expand it’s occupied memory size by using realloc() as following:

#include <iostream>
using namespace std;
int n=2,* pint;
void Initialization()
{
	pint=new int[n];
}
void DoSomething(){}
int main()
{
	Initialization();
	DoSomething();
	pint=(int*)realloc(pint,(++n)*sizeof(int));
	pint[n-1]=123456;
	cout<<pint[n-1]<<endl;
	return 0;
}
</pre>
But when it comes to the two-dimensional pointer, it nolonger works if you write some code like this:
<pre lang="cpp" line="1" file="code2.cpp" colla="+">
#include <iostream>
using namespace std;
int n=2,len=20;
char** ppchar;
void Initialization(){
	ppchar=new char*[n];
	for(int i=0;i<n;i++){
		ppchar[i]=new char[len];
	}
}
void DoSomething(){}
int main()
{
	Initialization();
	DoSomething();
	ppchar=(char**)realloc(ppchar,(++n)*len*sizeof(char));
	ppchar[n-1]="this is a new one";
	cout<<ppchar[n-1]<<endl;
	return 0;
}

That is because you failed to notify the system, or in other words declare the address of ppchar[n-1].
And here is a correct version of the same function by adding a statement between line 16 and 17:

ppchar[n-1]=new char[len];

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.