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; }
#include<stdio.h> //The structure variable Lily is declared with struct person definition struct 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 definition struct movie LionKing; printf("Person and movie structures defined and their variables declared!\n"); return 0; }
#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 braces struct 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 braces struct person Henry = {"Henry Doug", 25, 6.1, 65.8}; //Data members are accessed with the "." operator printf("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; }
RELATED TAGS
CONTRIBUTOR
View all Courses