Previous | Home | Next |
Introduction of C structure
In some programming contexts, you need to access multiple data types under asingle name for easy manipulation; for example you want to refer to address with multiple data like house number, street, zip code, country C supports structure which allows you to wrap one or more variables with different data types. A structure can contain any valid data types like int, char, float even arrays and other structures. Each variable in structure is called a structure member.
Defining structure
To define a structure, you can use struct keyword.
struct struct_name{ structure_member };
The name of structure is followed the rule of variable name.
For example
1. struct address{ 2. unsigned int house_number; 3. char street_name[50]; 4. int zip_code; 5. char country[50]; 6. };
It contains house number as an positive integer, street name as a string, zip code as an integer and country as a string.
Declaring structure
The above example only defines an address structure without create any instance of it. To create or declare a structure you have two ways:
The first way is declare a structure follows by structure definition like this :
struct struct_name { structure_member; ... }
instance_1,instance_2 instance_n;
In the second way you can declare your structure instance at a different location in your source code after structure definition.
Here is structure declaration syntax :
struct struct_name instance_1,instance_2 instance_n;
Complex structure
Structure can contains arrays or other structures so it is sometimes called complex structure.
For example address structure is a complex structure. We can define a complex structure which contains address structure as follows:
struct customer{ char name[50]; structure address billing_addr; structure address shipping_addr; 5. };
Previous | Home | Next |