malloc()

<stdlib.h> This header defines several general purpose functions, including dynamic memory management, random number generation. The malloc function allocate a block of memory of specified size and returns a pointer of type void. The free function is used to deallocate the allocated memory. Progarm Program Source #include <stdio.h> #include <stdlib.h> int main() { int *ptr=(int*)malloc(sizeof(int)*3); ptr[0]=2; ptr[1]=4; ptr[2]=6; printf(“ptr … Read more…

malloc() another example(with for loop)

The malloc function allocate a block of memory of specified size and returns a pointer of type void. The free function is used to deallocate the allocated memory. Program Program Source #include <stdio.h> #include <stdlib.h> int main() { int *ptr=(int*)malloc(sizeof(int)*5); int i; for(i=0;i<5;i++) { ptr[i]=i; } for(i=0;i<5;i++) { printf(“ptr [%d] = %d\n”,i,ptr[i]); } free(ptr); return 0; }

malloc() another example(String)

The malloc function allocate a block of memory of specified size and returns a pointer of type void. The free function is used to deallocate the allocated memory. Program Program Source #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char *ptr=(char*)malloc(sizeof(char)*15); strcpy(ptr,”hajsoftutorial”); printf(“%s\n”,ptr); free(ptr); return 0; }

malloc() without Type cast

1) int *ptr=(int*)malloc(sizeof(int)*5); 2) int *ptr=malloc(sizeof(int)*5) Second type syntax does not contain type cast. This is implicit conversion. The void pointer returned by malloc is automatically converted to the pointer ptr type. So, both type memory allocation are same. Program Program Source #include <stdio.h> #include <stdlib.h> int main() { int *ptr=malloc(sizeof(int)*5); int i; for(i=0;i<5;i++) { ptr[i]=i; … Read more…