C malloc() functionPritesh
Malloc Function : Dynamic memory allocation
ptr = (data_type *)malloc(No_of_elements*sizeof(data_type));
Steps to Understand :
1 . (data_type *):
- Type conversion or typecasting refers to changing an entity of one data type into another.
- Example : if we assign the integer 4 to floating variable then internally it is assigned as 4.00
- Similarly , Address of Block of memory is casted to address of Pointer .
2 . No_of_elements :
- No_of_elements is nothing but the “No of elements Created at run time”.
- i.e Suppose we want to allocate space for 10 integer variable then No_of_elements = 10
3 . Sizeof(data_type)
- Note Carefully : Sizeof is not function , it is Operator
- Sizeof operator calculates the memory required for variable,data type etc
- In malloc size of data_type is written .Data types specified in the first step must match with data type in this step.
Note : Example
ptr = (int *) malloc (10 * sizeof(int));
- Header File : stdlib.h
- Allocate 20 bytes of memory
- Sizeof Returns the Size of Parameter specified
- 10 means allocate space at run time for 10 elements
- (int *) means Typecasting i.e Address of Block of memory is casted to address of Pointer
- On Success : 20 bytes will be allocated
- On Fail : Returns NULL
- Memory Address is assigned to Pointer ptr
- Clears allocated memory to garbage value