A structure (or struct) is a user-defined data type that groups multiple data items, of possibly different data types, into a single collection. Structures can make your C code cleaner and more meaningful as logically related data is clumped together, and code reusability is encouraged.
Structures are defined with the struct
keyword followed by the structure’s name and parenthesis that encompass a list of member data items. A sample structure is defined below.
#include<stdio.h>struct person {char name[50];int age;double height;double weight;};int main() {printf("Person structure defined!\n");return 0;}
Now that we know how to define structures, we would like to declare them. A structure variable can be declared alongside the structure definition or separately, like standard data types. Both declarations are shown below:
#include<stdio.h>//The structure variable Lily is declared with struct person definitionstruct person {char name[50];int age;double height;double weight;} Lily;struct movie {char title[50];char director[50];int runtime;int id;int rating;};int main() {//The structure variable LionKing separately away from struct movie definitionstruct movie LionKing;printf("Person and movie structures defined and their variables declared!\n");return 0;}
Next, we need to learn how to store values to our structure data items. This cannot be done at the time of structure definition, but it can be done after a structure variable has been declared. Below is an example:
#include<stdio.h>struct person {char name[50];int age;double height;double weight;};int main() {//Data members are initialized in order of their declaration in the person struct using curly bracesstruct person Henry = {"Henry Doug", 25, 6.1, 65.8};printf("Data members successfully initialized!");return 0;}
Finally, we want to make use of our structure’s data items by accessing them. The binary dot (.) operator can be used for this purpose. Here’s an example showing how:
#include<stdio.h>struct person {char name[50];int age;double height;double weight;};int main() {//Data members are initialized in order of their declaration in the person struct using curly bracesstruct person Henry = {"Henry Doug", 25, 6.1, 65.8};//Data members are accessed with the "." operatorprintf("Name of person: %s", Henry.name);printf("\nAge of person: %d", Henry.age);printf("\nHeight of person: %1f", Henry.height);printf("\nWeight of person: %1f", Henry.weight);return 0;}
The following example illustrates how structures can be used to calculate the slope of a line passing through two points on a 2D plane.
#include<stdio.h>struct Point {double x;double y;};int main() {struct Point point1 = {0.5, 6.4};struct Point point2 = {1.5, 4.2};double gradient = (point2.y - point1.y)/(point2.x - point1.x);printf("Gradient: %lf", gradient);return 0;}
Free Resources