Structs in C
Purpose
- To create structs
- Access struct data
- Write functions that use and manipulate structs
Download Files
Exercise
- weatherday.h contains the struct definition of WeatherDay. In weatherday.c, declare declare a static variable called day1 of type WeatherDay in function
main().
- Initialize each value of struct day1 to value of your choice
- Now create a pointer of type WeatherDay (call it dayptr) and set it to point to variable day1 in function
main()
- Complete the
printWD() in weatherday.c to print data of the WeatherDay struct
- Note that function printWD takes a pointer to struct WeatherDay, so use the speacial notation ->
- Call the print(dayptr) in main function and see if prints the values you intialized in part 1
- Complete function avgTemp in weatherday.c. Call it in main function to give you the average temperature for dayptr.
- Complete intialize(WeatherDay * day) in weatherday.c, such that all the data of day is intialized to zero
- In
main(), call initialize(dayptr), and then call printDW(ptr), to see if the data values of the of the struct pointed by dayptr are intialized to zero
- What would happen if function intialize in weatherday.c was written such that its input parameter was a variable of type WeatherDay and not WeatherDay * ?
- Instead of intializing the data of day1, ask user to enter the values. Use dayptr to scan in the values using
scanf().
- Create a dynamic array of WeatherDay of size 5.
- Access the third element of the array and intialize the data to value of your choice. Then call the printDW and avgTemp for the third element.
- Now, for each element of the array, intialize the struct data to all zeros.
- Before exiting the program, remember to free the pointer used to allocate dynamic memory
Created by Diana Palsetia