Array C Programing

Dynamic Memory Allocation :

C language requires the number of elements in an array to be specified at compile time. Many languages permit a programmer to specify an army’s size at run time. Such languages have the ability to calculate and assign, during execution, the memory space required by the variables in the program. The process of allocating memory at run time is known as dynamic memory allocation. Although C does not inherently have this facility, there are four library routines known as "memory management functions", that can be used for allocating and freeing memory during program execution.

 

 

Memory Allocation Functions

Functions  Task
Malloc Allocates requested size of bytes and returns a pointer to the first byte, of allocated space.
Calloc Allocates spaces for an array of elements, initializes them to zero.

Free Frees previously allocated space.
Realloc iModifies the size of previously allocated space.

 

Malloc :

A block of memory may be allocated using the function malloc. The malloc function reserves a block of memory of specified size and return a pointer of type void. It takes the form.

ptr*=(cast-type*)malloc(byte-size);

 

Ptr is a pointer of type cast-type. The malloc returns a pointer to an area of memory with size byte-size.

For Example : x = (int *) malloc (100 * size of (int)):

 

 

Calloc:

It is another memory allocation function that is normally used for requesting memory space at runtime for storing derived data types such as arrays and structures while malloc allocates a single block of storage space, calloc allocates multiple blocks of storage, each of the same size and then sets all bytes to zero. The general form of calloc is:

ptr=(cast-type*)calloc(n,elem-size);

 

Free :

Compile time storage of a variable is allocated and released by the system in accordance with its storage class. With dynamic run-time allocation we can release the space when it is not- required. We may release- that block of memory for future use, using the free function.

free (ptr); 

 

Realloc:

We can change the memory size already allocated with the help of realloc. This process is called the reallocation of memory. For Example, if the original allocation is done by statement.

Ptr = malloc (size);

Then reallocation of space may be done by statement

ptr= realloc( ptr, newsize);