In: Computer Science
Write C Code for the following question which has two parts:
a) Show how a typedef statement can be used to declare a new data type – to demonstrate this create a new type called Person which is the structure declared previously.
b) Write C code to declare an array of 50 pointers to Persons. Using a loop, use malloc to dynamically allocate memory for each of these structures. There is no need to put any values into the structures. Use a second loop to then deallocate each structure.
a)
The structure declared which is represented by typedef is provided below:
typedef struct Person;
Explanation:
b)
The declaration of array of 50 pointers to Person structure is as follows:
struct person *Person;
Using for loop, allocation of memory using malloc is provided below:
for(int i = 0; i < 50; i++)
{
Person = (struct Person*)malloc(50 * sizeof(struct Person));
}
Using second for loop, deallocation of the structure is provided below:
for(int i = 0; i < 50; i++)
{
free(Person);
}
The complete code of C programming is provided below:
Screenshot of the code:
Code To Copy:
//Include the header file.
#include <stdio.h>
#include <malloc.h>
//Define the structure Person.
struct Person{
};
//Define the main function.
int main(void) {
//Declare an pointer of structure Person.
struct person *Person;
//Allocate memory for 50 persons using malloc.
for(int i = 0; i < 50; i++)
{
Person = (struct Person*)malloc(50 * sizeof(struct
Person));
}
//Deallocate the memory for 50 persons.
for(int i = 0; i < 50; i++)
{
free(Person);
}
}