3️⃣

4.3 Applications of Structures

 

When to use a structure

 
Structures, simply put, are a way to organize a collection of values. Considering the various other ways to organize data (ex. arrays), when should a structure be used?
 
Generally, use a structure if you:
  • Are grouping multiple different data types together
  • Have a small memory footprint
  • Have fields which would only be initialized to their default values (for example, all Boolean types are initialized to false and all numeric types are initialized to 0 .
 
These conditions become more important when identifying the difference between a structure and a class, as they are extremely similar!

Structures as parameters

 
If you would like to pass a structure into a method as a parameter, you cannot simply pass the entire object.
 
The following code will throw an error:
struct class{ // String variable char title[50]; } void useClass(struct class) { // Use your struct return; } int main() { struct class biology; useClass(biology); // Will throw an error }
 
Instead, you must use a reference to pass the struct so that the method can access and modify the values within it. This can be done by passing a pointer into a function:
 
struct book{ // Properties of struct char title[50]; int bookID; } void useBook(struct book *c) { // Use your struct here return; } int main() { // Initialize class struct book biology; book.bookID = 120; struct book *biologyptr = &biology; // Pass pointer into parameter useBook(biologyptr); }
 

Previous Section

Next Chapter

 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.