Now that we’ve leveraged that power of structures to package variables together we can discuss how we can access each member variable individually using dot notation.
Dot notation is a C operator that allows you to access and modify a member variable of a structure.
struct Bottle { char* name; int maxCapacity; int currentCapacity; }; struct Bottle myBottle = {"Medium Bottle", 24, 0}; // Fill some of myBottle myBottle.currentCapacity = 10; printf("The bottle is now filled to %d", myBottle.currentCapacity);
In the example above:
- A bottle structure is defined and initialized with the variable
myBottle
- The member variable
currentCapacity
is accessed and set to10
withmyBottle.currentCapacity = 10
- The same variable is accessed again using the dot operator and output with
printf()
You can also use the dot operator to initialize a structure if you’d like to declare it first without initializing it right away like:
struct Bottle myBottle; myBottle.name = "Medium Bottle"; myBottle.maxCapacity = 24; myBottle.currentCapacity = 0;
The dot operator is essential in enhancing the packaging benefits of structs by allowing you to access any of the Bottle
member variables through the variable myBottle
.
Instructions
The workspace has defined a Person
struct. Inside the main()
function, person1
and person2
are initialized as Person
types and the names of each have also been set.
Following the initialization and using dot notation:
- Set the
age
ofperson1
to57
- Set the
age
ofperson2
to27