Unit - 9
Unit - 9
Jigar Dalvadi
C malloc() Method
malloc() is a method in C which is used to allocate a memory block in the heap section
of the memory of some specified size (in bytes) during the run-time of a C program.
It is a library function present in the <stdlib.h> header file.
Syntax of malloc()
ptr = (castType*) malloc(size);
Example
ptr = (float*) malloc(100 * sizeof(float));
1|P ag e
PPS – 3110003 Prepared By: Prof. Jigar Dalvadi
#include <stdio.h>
#include <stdlib.h>
int main()
{
// Dynamically allocated variable, sizeof(char) = 1 byte.
char *ptr = (char * )malloc(sizeof(char));
if (ptr == NULL)
{
printf("Memory Error!\n");
}
else
{
*ptr = 'S';
printf("%c", *ptr);
}
return 0;
}
C calloc() Method
calloc() is a method in C which is also used to allocate memory blocks in the heap
section, but it is generally used to allocate a sequence of memory blocks (contiguous
memory) like an array of elements.
It is also present in <stdlib.h> header file.
Syntax of malloc()
ptr = (castType*)calloc(n, size);
Example
ptr = (float*) calloc(25, sizeof(float));
2|P ag e
PPS – 3110003 Prepared By: Prof. Jigar Dalvadi
}
else
{
// initializing array with char variables
for (int i = 0; i < n; i++)
{
char ch;
scanf("%c", &ch);
*(str + i) = ch;
}
// printing array using pointer
for (int i = 0; i < n; i++) {
printf("%c", *(str + i));
}
}
return 0;
}
3|P ag e