In C, write a simple program to define a struct template and define it as a data
ID: 3818703 • Letter: I
Question
In C, write a simple program to define a struct template and define it as a datatype using typedef.
Than allocate a block of dynamically allocated memory and set the values for the different members.
Than have them print out the contents. It should like this
struct patient{
char name[20];
int age;
float weight;
float height;
int pulse_rate;
};
than do a typedef:
typedef patient Paitent;
than allocate a block of memory of type patient and asign values to the members as follows:
name:your own name or any fictional name you want
age:23
weight: 200.5 (lbs)
height: 72.2 (inches)
pulse_rate: 65
They can pick any values they want,then print out the values.
Explanation / Answer
Ans:
#include<stdio.h>
#include<stdlib.h> //for malloc
#include<string.h>
struct patient
{
char name[20];
int age;
float weight;
float height;
int pulse_rate;
};
void main()
{
typedef patient Patient; //typedef definition used now we have new variable type Patient
Patient *P; // Patient type pointer variable declared
P=(Patient*)malloc(50*sizeof(Patient)); //dynamically allocating memory by malloc
if(P==NULL)
{ printf("couldn't allocate memory ");
}
else
{
strcpy(P->name,"Daniel"); //directly asigning values to the members
P->age=34;
P->weight=180.0;
P->height=70.3;
P->pulse_rate=60;
}
printf("Details are: ");
printf("name:%s ",P->name);
printf("age:%d ",P->age);
printf("pulse_rate:%d ",P->pulse_rate);
printf("height:%f ",P->height);
printf("weight:%f ",P->weight);
}