Pointers - 10 Pointer & Structure Method 2

  Pointer & Structure :

Method 2 : using dynamic memory allocation 


  Allocating memory for large data at compile time is rarely practical. Specially if the data objects are used infrequently and for a short time. Instead  we usually allocate memory for these data object at runtime.

To make more memory available to the programmer C provides a number of function for allocating memory at runtime viz, malloc(), realloc(), calloc() and free(); 


    In this case we use malloc() function to allocate memory to a structure variable and then stores the memory address of allocated location in memory will be assigned to pointer. Later we access members through this pointer. To use malloc() function include stdlib.h header file. 

Syntax for malloc() :

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


/* Example : program to read and print n number of student details */

# include < stdio.h >
struct student
{
char name[30];
int s1, s2, s3, total;
};

main()
{
 struct student *p;
int n, i;

printf( "\n Enter the number of students : ") ;
scanf( "%d", &n);

p =  (struct student * ) malloc ( n * sizeof(struct student) );

for ( i = 0; i < n; i++)
{
printf ( " \n Enter the Name and Marks for Subject1, Subject2, Subject3 \n " );

scanf ("%s%d%d%d", (p+i)->name, &(p+i)->s1, &(p+i)->s2, &(p+i)->s3 );
(p+i)->total = (p+i) -> s1 + (p+i) -> s2 + (p+i) -> s3;
}

printf ( "\n Students details are \n " );

for ( i = 0; i < n; i++)
{
 printf ( "\n Name=%s \n Subject1=%d \n Subject2 = %d \n Subject3 =%d\nTotal=%d",(p+i)->name,(p+i)->s1,(p+i)->s2,(p+i)->s3,
(p+i)->total);
}

}

Comments