Search⌘ K
AI Features

Solution Review: Dynamically Allocate Space for Two Structures

Understand how to dynamically allocate memory for two structures using pointers and malloc in C. This lesson reviews typecasting void pointers returned by malloc to specific struct pointers and managing memory on the heap.

We'll cover the following...

Solution

See the code given below!

C
#include <stdio.h>
#include <stdlib.h>
struct Address
{
char Houseno[ 20 ], Street[30], City[25] ;
long int Pincode ;
} ;
struct Employee
{
char Name[30] ;
int Age ;
struct Address add ;
float Salary ;
} ;
int main( )
{
struct Employee *p2;
struct Address *p1;
p1 = ( struct Address * ) malloc ( sizeof ( struct Address ) ) ;
p2 = ( struct Employee * ) malloc ( sizeof ( struct Employee ) ) ;
}

Explanation

p1 and p2 are pointers that are ...