...
/Coding Challenge: Modeling Complex Objects and Relationships (2)
Coding Challenge: Modeling Complex Objects and Relationships (2)
Practice everything learned so far by building an application to handle a flower business.
Task 6: Coding challenge
Now we have all the pieces needed to open a TFlowerShop
, which we’ll add to the flower shops list using the function from Task 4. We’ll initialize the two flowers using the function from Task 5.
Write a function called openFlowerShop
, which will allocate, initialize, and return a pointer to a TFlowerShop
structure.
The function header is:
TFlowerShop* openFlowerShop(TFlowerBusiness* flowerBusiness, int continentId, char* name, char* address, int openingYear)
flowerBusiness
is the current business.continentId
is the ID of the continent where we want to open the business.name
,address
, andopeningYear
are used to initialize some of the members inside theTFLowerShop
.- The function must return
NULL
on failure. - It must also make sure to allocate and initialize all the members correctly.
- After we allocate the flower shop, we must add it to the flower shops list of that continent. You may want to use the function from Task 4, but check its return value and guard against
realloc
fails. - What happens if this shop is the first shop in the continent? In other words, this is the first time our business opens a shop in the new continent. You may want to use the function
allocContinent
from Task 3.
This task is the most challenging task in the whole project. Make sure to pay special attention to it.
Press + to interact
TFlowerShop* openFlowerShop(TFlowerBusiness* flowerBusiness, int continentId, char* name, char* address, int openingYear){return NULL;}
Press the “Show Solution” button to view the solution. The main workflow is as follows:
- Allocate and fully initialize a flower shop, making use of
addFlowersToFlowerShop
. - Check if we are already present on the continent where we want to open this shop.
- If not, allocate the continent using
allocContinent
. - If the allocation fails, clean up the shop.
- If not, allocate the continent using
- Add the flower shop to the list of flower shops using the function
addFlowerShopToList
.- If the addition fails, it may be a
realloc
fail. - Clean up the shop.
- Clean up the continent only if it’s empty. This scenario can happen if we just allocated it and wanted to add the first shop but failed. Reset all the pointers to
NULL
so, at a later point, we know that we freed the memory and must reallocate.
- If the addition fails, it may be a
Task 7:Demo task
At ...