In C language we used malloc () and calloc () function for dynamic memory allocation. The memory allocated through malloc () or calloc () functions can be vacated using free () function. C++ language provides a better way to accomplish the same job through the use of new and delete operators. The new operator allocates memory from the free store while delete operator returns the memory to the free store.
#include< iostream.h >
#include < conio.h >
#include< string.h >
void main ()
{
clrscr ();
int len;
char *str1;
char *str="Satavisha.";
len= strlen (str);
str1=new char [len+1];
strcpy (str1, str);
cout<< str1;
getch ();
}
Another C++ program of same type.
#include< iostream.h >
#include< conio.h >
#include< stdio.h >
class person
{
private:
char name [40];
public:
void setName ()
{
puts ("Enter Name: -");
gets (name);
}
void display ()
{
cout<< "\nName is: -"< <name;
}
};
void main ()
{
clrscr ();
person *ptr [10];
int n=0;
char choice;
do
{
ptr [n]=new person;
ptr [n]->setName ();
n++;
fflush (stdin);
cout<< "Another (y/n): -";
cin >>choice;
} while (choice=='y');
for (int i=0;i< n; i++)
{
ptr [i]->display ();
}
getch ();
}
No comments:
Post a Comment