Structures
A structure is used to group different types of data together. It is defined using the struct
keyword.
Syntax
struct Name{
type1 memberName1;
type2 memberName2;
type3 memberName3;
...
typeN memberNameN;
};
A structure is made up of members where each memberName
has to be declared with a type
.
Example
The following example uses the struct
keyword to create a Patient
structure:
struct Patient{char name[30];int age;int weight;int heightInInches;};
name
, age
, weight
, and heightInInches
are members of the Patient
structure.
Structure Variables
Variables can be created in order to work with the Patient
structure above. The following example declares and initializes a structure variable:
#include <stdio.h>#include <string.h>struct Patient {char name[30];int age;int weight;int heightInInches;};int main() {// Variable initialization at declarationstruct Patient patientA = {"Douglas Franklin", 62, 280, 74};return 0;}
Accessing Members
Members can be accessed using the member operator .
:
#include <stdio.h>#include <string.h>struct Patient {char name[30];int age;int weight;int heightInInches;};int main() {// Variable initialization at declarationstruct Patient patientA = {"Douglas Franklin", 62, 280, 74};// Accessing membersprintf("Name: %s \nAge: %d \nWeight: %d \nHeight: %d\n",patientA.name, patientA.age, patientA.weight, patientA.heightInInches);return 0;}
This will output the following:
Name: Douglas FranklinAge: 62Weight: 280Height: 74
Nested Structures
A structure can be within another structure. Nested structure members can be accessed using the member operator .
. The example below shows a Hospital
structure member variable being declared within the Patient
structure:
#include <stdio.h>#include <string.h>struct Hospital {char department[30];int roomNum;};struct Patient {char name[30];int age;int weight;int heightInInches;struct Hospital roomDetails;};int main() {// Variable initialization at declarationstruct Patient patientA = {"Douglas Franklin", 62, 280, 74, "oncology", 526};// Accessing nested structure membersprintf("Department: %s \nRoom: %d \n", patientA.roomDetails.department, patientA.roomDetails.roomNum);return 0;}
The output is as follows:
Department: oncologyRoom: 526
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.