Let’s wrap up by using structures with functions.
We can specify structures and pointers to structures as parameters to functions:
void myFunction(struct Bottle b, struct Bottle* bPointer)
When passing a structure to a function:
- A copy of the structure is made so memory usage is a concern
- Any modifications made to the structure will not affect the original structure, only the copy
When passing a pointer to a structure:
- Because the pointer is the address of the original structure any modifications to the member variables will affect the original structure
void bottleFunction(struct Bottle b, struct Bottle* bPointer){ b.name = "Super Large"; b.maxCapacity = 100; bPointer->name = "Super Small"; bPointer->maxCapacity = 4; } int main(){ struct Bottle b1 = {"Medium", 24, 9}; struct Bottle b2 = {"Large", 35, 9}; bottleFunction(b1, &b2); }
In the above example:
bottleFunction
has 2 parameters, aBottle
structure and a pointer to aBottle
structure- Inside the function, the structures are accessed the same as they would whether it is a structure or pointer to a structure.
- The first argument in the call to
bottleFunction()
insidemain()
isb1
. A copy of this structure is made withinbottleFunction()
and no changes can be made to the values ofb1
inmain()
- The second argument in the call to
bottleFunction()
is&b2
: the address ofb2
. Any change to the member variables using this address will change the values ofb2
inmain()
We can also return structures by setting the return type in the function signature:
struct Bottle getEmptyBottle(void){ struct Bottle b = {"My Bottle", 24, 0}; return b; }
Notice that structures as parameters and as the return type must use the struct
keyword.
Instructions
Time to look at different ways we can work with structures within functions.
In script.c:
- Define the function
ageOne()
- Give the function a return type of
Person
- The body can be empty.
Remember to use the keyword struct
throughout this definition.
Add some parameters to the ageOne()
function definition:
- The first function parameter should be called
friend1
and be of typePerson
- The second parameter should be called
friend2Pointer
and be a pointer to typePerson
Now modify the age
member variables within the structures.
Inside ageOne()
:
- Add
1
to theage
variable infriend1
- Using the arrow format to dereference, add
1
to theage
variable in the structure pointed to byfriend2Pointer
- Return the structure
friend1
Now test it all out! There are 2 structures defined in main()
to work with the function you created.
Inside the main()
function:
- Call
ageOne()
and assign the return value tomyFriend
- Set the first argument of
ageOne()
tomyFriend
- Set the 2nd argument of
ageOne()
to the address ofmyOtherFriend
Run the code and see how the data changes.