EX 1 A
Declare a calendar as an array of 7 elements (A dynamically Created array) to represent 7 days of a week. Each Element of the array is a structure having three fields. The first field is the name of the Day (A dynamically allocated String), The second field is the date of the Day (A integer), the third field is the description of the activity for a particular day (A dynamically allocated String).
Key Points:
Struct
Day
: Holdsday_name
,date
, andactivity
(all dynamically allocated strings exceptdate
).createDay()
: Allocates memory for aDay
struct and its strings.freeDay()
: Frees memory for aDay
struct and its strings.Main Function:
Creates an array of 7
Day*
for each day of the week.Initializes each day with a name, date, and activity.
Prints out the weekly calendar.
Frees all allocated memory.
Purpose:
Demonstrates dynamic memory allocation, struct usage, and memory cleanup in C.
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Structure to represent a day's activity
struct Day {
char* day_name;
int date;
char* activity;
};
// Function to initialize a day structure
struct Day* createDay(const char* name, int date, const char* activity) {
struct Day* newDay = (struct Day*)malloc(sizeof(struct Day));
if (newDay == NULL) {
perror("Memory allocation failed");
exit(1);
}
newDay->day_name = strdup(name);
newDay->date = date;
newDay->activity = strdup(activity);
return newDay;
}
// Function to release memory for a day structure
void freeDay(struct Day* day)
{
free(day->day_name);
free(day->activity);
free(day);
}
int main() {
// Create an array of 7 day structures
struct Day* calendar[7];
// Initialize each day in the calendar
calendar[0] = createDay("Monday", 1, "Working on project A");
calendar[1] = createDay("Tuesday", 2, "Meetings with team");
calendar[2] = createDay("Wednesday", 3, "Preparing presentation");
calendar[3] = createDay("Thursday", 4, "Workshops on new technology");
calendar[4] = createDay("Friday", 5, "Finishing report");
calendar[5] = createDay("Saturday", 6, "Family's outing");
calendar[6] = createDay("Sunday", 7, "Relaxing and unwind");
// Display the calendar
for (int i = 0; i < 7; i++) {
printf("Day %s (Date %d):\n", calendar[i]->day_name, calendar[i]->date);
printf("Activity: %s\n", calendar[i]->activity);
printf("\n");
}
// Free memory for each day in the calendar
for (int i = 0; i < 7; i++) {
freeDay(calendar[i]);
}
return 0;
}
Output:
No comments:
Post a Comment