C Program to Store Information Using Structures with Dynamic Memory Allocation

C Program to Store Information Using Structures with Dynamic Memory Allocation

397
1
SHARE

C Program to Store Information Using Structures with Dynamic Memory Allocation : This program asks user to store the value of n and allocates the memory for the n structure variable dynamically using malloc() function.

C Program to Store Information Using Structures with Dynamic Memory Allocation :

#include <stdio.h>
#include<stdlib.h>
struct name {
   int a;
   char c[30];
};
int main(){
   struct name *ptr;
   int i,n;
   printf("Enter n: ");
   scanf("%d",&n);

/* Allocates the memory for n structures with pointer ptr pointing to the base address. */
   ptr=(struct name*)malloc(n*sizeof(struct name));
   for(i=0;i<n;++i){
       printf("Enter string and integer respectively:\n");
       scanf("%s%d",&(ptr+i)->c, &(ptr+i)->a);
   }
   printf("Displaying Infromation:\n");
   for(i=0;i<n;++i)
       printf("%s\t%d\t\n",(ptr+i)->c,(ptr+i)->a);
   return 0;
}

 

OUTPUT:

Enter n: 2
Enter string and integer  respectively:
CProgramming
22
Enter string, integer and floating number  respectively:
Structure
33

Displaying Information:
CProgramming      22      
Structure        33

 

 

1 COMMENT

  1. Yoᥙ reallly makе it appear so easy ᴡith youг presentation howeger Ⅰ find this topic to be
    reаlly one thing ѡhich І beliee ӏ’d bу no mеans understand.
    It kіnd of feels toο complicated ɑnd extremely wide
    fⲟr me. ӏ am taking a looҝ ahead fοr yoսr next
    publish, I will attempt tօ get the cling off іt!

LEAVE A REPLY