Structures
Structures are collections of variables grouped together under a common name. The variables within a structure are referred to as the structure’s members and may be accessed individually as needed.
Structures:
- May contain any number of members
- Members may be of any data type
- Allow group of related variables to be treated as a single unit, even if different types
- Ease the organization of complicated data
Creating a Structure Definition
Syntax
struct structName
{
type1 memberName1;
…
typen memberNamen;
}
Example
|
1
2
3
4
5
6
|
// Structure to handle complex numbersstruct complex{ float re; // Real part float im; // Imaginary part} |
Syntax
struct structName
{
type1 memberName1;
…
typen memberNamen;
} varName1 ,…, varNamen;
Example
|
1
2
3
4
5
6
|
// Structure to handle complex numbersstruct complex{ float re; float im; } x, y; // Declare x and y of type complex |
Declaring a Structure Variable (Method 2)
Syntax
If structName has already been defined:
struct structName varName1 ,…, varNamen;
Example
|
1
2
3
4
5
6
7
|
struct complex{ float re; float im; } ...struct complex x, y; // Declare x and y of type complex |
structVariableName.memberName
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
struct complex{float re;float im;} x, y; //Declare x and y of type complexint main (void){ x.re = 1.25; // Initialize real part of x x.im = 2.50; // Initialize imaginary part of x y = x; // Set struct y equal to struct x...} |
typedef struct structTagoptional
{
type1 memberName1;
…
typen memberNamen;
} typeName;
|
1
2
3
4
5
6
|
// Structure type to handle complex numberstypedef struct{ float re; // Real part float im; // Imaginary part} complex; |
If typeName has already been defined:
typeName varName1 ,…, varNamen;
The keyword struct is no longer required!
|
1
2
3
4
5
6
7
|
typedef struct{ float re; float im; } complex; ...complex x, y; // Declare x and y of type complex |
If typeName or structName has already been defined:
typeName varName = {const1 ,…, constn};
or
struct structName varName = {const1 ,…, constn};
|
1
2
3
4
5
6
7
|
typedef struct{ float re; float im; } complex; ...complex x = {1.25, 2.50}; // x.re = 1.25, x.im = 2.50 |