1) Malloc in C :
malloc() is used to allocate memory space in bytes for variables of any valid C data type.Syntax :
pointer= (data_type*)malloc(user_defined_size); |
malloc.c
#include<stdio.h> #include<conio.h> #include<stdlib.h> void main() { int a,*ptr; a=10; ptr=(int*)malloc(a*sizeof(int)); ptr=a; printf("%d",ptr); free(ptr); getch(); } |
- #include<stdio.h> header file is included because, the C in-built statementprintf we used in this program comes under stdio.h header files.
- #include<conio.h> is used because the C in-built function getch() comes under conio.h header files.
- stdlib.h is used because malloc() comes under it.
- int type variable a and pointer *ptr are declared.
- Variable a is assigned a value of 10.
- malloc() is used to allocate memory to pointer ptr.
- The size given through malloc() to ptr is sizeof(int).
- Now ptr is assigned the value of a. ptr=a; so the value 10 is assigned to ptr, for which, we dynamically allocated memory space using malloc.
- The value in ptr is displayed using printf
- Then allocated memory is freed using the C in-built function free().
2) Calloc in C :
calloc() is sued to allocate multiple blocks of memory dynamically during the execution (run-time) of the program.Syntax :
pointer=(data_type*)calloc(no of memory blocks, size of each block in bytes); |
calloc.c
#include<stdio.h> #include<conio.h> #include<stdlib.h> void main() { int *ptr,a[6]={1,2,3,4,5,6}; int i; ptr=(int*)calloc(a[6]*sizeof(int),2); for(i=0;i<7;i++) { printf("\n %d",*ptr+a[i]); } free(ptr); getch(); } |
- #include<stdio.h> header file is included because, the C in-built statementprintf we used in this program comes under stdio.h header files.
- #include<conio.h> is used because the C in-built function getch() comes under conio.h header files.
- stdlib.h is used because malloc() comes under it.
- A Pointer *ptr of type int and array a[6] is declared.
- Array a[6] is assigned with 6 values.
- Another variable i of type int is declared.
- Calloc() is used to allocate memory for ptr. 6 blocks of memory is allocated with each block having 2 bytes of space.
- Now variable i is used in for to cycle the loop 6 times on incremental mode.
- On each cycle the data in allocated memory in ptr is printed using *ptr+a[i].
- Then the memory space is freed using free(ptr).
No comments:
Post a Comment