Allocating Memory Dynamically
The two functions for allocating memory, malloc( ) and calloc( ), have slightly different parameters:
void *malloc( size_t size );
The malloc( ) function reserves a contiguous memory block whose size in bytes is at least size. When a program obtains a memory block through malloc( ), its contents are undetermined.
void *calloc( size_t count, size_t size );
The calloc( ) function reserves a block of memory whose size in bytes is at least count x size. In other words, the block is large enough to hold an array of count elements, each of which takes up size bytes. Furthermore, calloc( ) initializes every byte of the memory with the value 0.
Both functions return a pointer to void, also called a typeless pointer. The pointer’s value is the address of the first byte in the memory block allocated, or a null pointer if the memory requested is not available.
Example
#include <stdio.h> int main() { char *a; int *b; // (typecast to data type)malloc(sizeof(data type)); a = (char *) malloc(sizeof(char) * 10); a = "hello"; printf("%s", a); // (typecast to data type)calloc(size,sizeof(data type)); b = (int *) calloc(10, sizeof(int)); // all elements initialized to 0 printf("\nFirst Element %d", *b); printf("\nSecond Element %d", *(b + 1)); printf("\nThird Element %d", *(b + 2)); printf("\nfourth Element %d", *(b + 3)); getchar(); return 0; }