In: Computer Science
Write a C program that contains a structure that uses predefined types and union. • Create a struct with name, age, kind (Either child, college student, or adult), and kindOfPerson (Either kid, student, or adult) • kids have a school field. Students have college and gpa. Adults have company and salary. • Create one non-dynamic struct with the content for a college student: "Bob", 20, K-State, 3.5 • Create one struct dynamically for a kid with: "Alison", 10, "Amanda Arnold Elementary" • Implement a function that can be used to display the contents of a single structure • Print out both structures • Free up the memory allocated before exiting
Simple structure
#include<stdio.h>
#include<string.h>
struct str1
{
char name[20];
int age;
char kind[20];
char kindOfPerson[20]
};
Non dynamic struct :
struct student
{
char name[20];
int age;
char college[30];
double salary;
};
int main()
{
struct student record = {0}; //initializing null
strcpy(record.name,"Bob");
record.age=20;
strcpy(record.college,"K-State");
record.salary=3.5;
printf(" Name is: %d \n", record.name);
printf(" Age is: %d \n", record.age);
printf(" College is: %d \n", record.college);
printf(" Salary is: %d \n", record.salary);
}
Dynamic structure:
#include<stdio.h>
#include<stdlib.h>
struct kid { char name[20]; int age; char school[30]; }; int main() { struct kid *ptr; int i, noOfRecords; printf("Enter number of records: "); scanf("%d", &noOfRecords); // Allocates the memory for noOfRecords structures with pointer ptr pointing to the base address. ptr = (struct kid*) malloc (noOfRecords * sizeof(struct course)); for(i = 0; i < noOfRecords; ++i) { printf("Enter name,age and school of the kid respectively:\n"); scanf("%s %d %s", &(ptr+i)->name, &(ptr+i)->age, &(ptr+i)->school); } printf("Displaying Information:\n"); for(i = 0; i < noOfRecords ; ++i) printf("%s\t%d\n%d\n", (ptr+i)->name, (ptr+i)->age, (ptr+i)->school); return 0; }
Implementing function
For ex if we want to display the contents of structure student then we can write a function as shown below :
void display(struct student stu) // in arguments the structure name is passed
{
//print details
}