C uses malloc() and calloc() function to allocate memory dynamically at runtime. Similarly it uses the function free() to free dynamically allocated memory.
New operator can be used to create objects of any type.It takes the following general form:
pointer-variable=new data type;
New pointer is the pointer of point data type. The new operator allocates insufficient memory to hold data object of type data type and return the address of the object. Data type may be any valid data type.
The pointer variable hold address of the memory space allocated.
e.g. (i) p= new int;
q=new float;
where p is a pointer of type int and q is the pointer of type float.
Remember p and q must have already been declared as pointer of appropriate types.
Alternatively the declaration of pointers and their assignment can be combined as follows:
int *p=new int;
float *q=new float;
Subsequently, the statements
* p=25;
*q=7.5;
assign 25 to the newly created int object and 7.5 to float object.
Also the memory using new operator can be initialised as follows:
(ii) int *p=new int (25);
float *q=new float(7.5);
-->* new can be used to create a memory space for any data type includinguser defined classes.
General form for a one dimensional array is
pointer-variable=new data-type[size]
Here size specifices the number of element in the array;
int *p=new int[15];
creates a memory space for an array of 10 integer.P[0] will refer to the first element .P[1] to the second element and so on.
0 Comment(s)