Write a C program to demonstrate dynamic memory allocation for structure and union.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* structure with 32 byte char array and integer */
struct cinema {
char name[32];
int rating;
};
/* union with 32 byte character array and integer */
union theater {
char name[32];
int noOfShows;
};
int main() {
struct cinema *c1;
union theater *t1;
/* dynamically allocate memory for structure and union variables */
c1 = (struct cinema *)malloc(sizeof(struct cinema));
t1 = (union theater *)malloc(sizeof(union theater));
/* assinging data to structure elements */
strcpy(c1->name, "Pursuit Of Happiness");
c1->rating = 10;
/* assigning data to union elements */
strcpy(t1->name, "Aries");
t1->noOfShows = 4;
/* printing the outputs */
printf("struct cinema {\nname = %s\n", c1->name);
printf("rating = %d\n}\n", c1->rating);
#include <stdlib.h>
#include <string.h>
/* structure with 32 byte char array and integer */
struct cinema {
char name[32];
int rating;
};
/* union with 32 byte character array and integer */
union theater {
char name[32];
int noOfShows;
};
int main() {
struct cinema *c1;
union theater *t1;
/* dynamically allocate memory for structure and union variables */
c1 = (struct cinema *)malloc(sizeof(struct cinema));
t1 = (union theater *)malloc(sizeof(union theater));
/* assinging data to structure elements */
strcpy(c1->name, "Pursuit Of Happiness");
c1->rating = 10;
/* assigning data to union elements */
strcpy(t1->name, "Aries");
t1->noOfShows = 4;
/* printing the outputs */
printf("struct cinema {\nname = %s\n", c1->name);
printf("rating = %d\n}\n", c1->rating);
/* contents of noOfShow will overwrite the contents in name */
printf("\nunion theater {\nname = %s\n", t1->name);
printf("noOfShows = %d\n}\n", t1->noOfShows);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
struct cinema {
name = Pursuit Of Happiness
rating = 10
}
union theater {
name = ^
noOfShows = 4
}
struct cinema {
name = Pursuit Of Happiness
rating = 10
}
union theater {
name = ^
noOfShows = 4
}
No comments:
Post a Comment