14-Dynamic Memory Allocation
14-Dynamic Memory Allocation
14-Dynamic Memory Allocation
ALLOCATION
Disadvantages of ARRAYS
General syntax:
ptr = (cast –type * ) malloc( byte-size ) ;
where ptr is pointer of any data type.
malloc returns a pointer to an area of
memory with size byte-size.
Example 1
int *ptr;
ptr = (int *) malloc ( 100 * (sizeof (int ) ) ;
int * ptr ;
printf ( “\n Enter the number of elements in the array “);
scanf(“%d”, &n);
ptr = ( int *) malloc ( n x sizeof ( int ) ) ;
int * ptr ;
ptr = ( int *) malloc ( 200 ) ;
Example 2
char * cptr ;
cptr = ( char * ) malloc ( 10 ) ;
This will allocate 10 bytes of memory space for the pointer cptr of type char.
? ? ? ? ? ? ? ? ? ?
10 bytes of space
Important
pointerpointer
*p *p pointer * p
Printing values in reverse order
pointer * p pointer
pointer
*p *p
OUTPUT
What is the size of array ? 5
Address of first byte : 077FA
Input values: 11 12 13 14 15
Also when the memory is allocated, all the elements are assigned a initial value of zero.
This is not provided by function malloc ( )
General syntax:
ptr = (cast _type * ) calloc (n, element_size);
The above statement allocates contiguous space
for n elements, each of size element_size.
example:
int **p;
Example: creating a 2D array of m rows and n columns.
int main()
{ int **ptr;
int m, n;
printf(“\n Enter the number of rows:”);
scanf(“%d”, &m);
printf(“\n Enter the number of columns:”);
scanf(“%d”, &n);
/* creating an array of m pointers */
ptr = (int**) malloc ( m *sizeof(int*));
/* allocating each pointer a row ( 1 D array) */
for (i = 0; i < m; i++)
ptr[i] = (int *)malloc( n * sizeof(int));
int **ptr
ptr[0]
ptr[1]
ptr[2]
ptr[3]
ptr[4]
Check This Out !!!
Is it possible to create a TWO Dimensional array with m rows, where each row will
have different number of columns ? ? ?
YES ! ! !
Visualization
Advantages