C Programming Structures

Last modified by Microchip on 2023/11/09 09:06

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 numbers
struct complex
{
 float re;    // Real part
 float im;    // Imaginary part
}

Back to Top

Declaring a Structure Variable (Method 1)

Syntax

struct structName
{
    type1 memberName1;
    ...
    typen memberNamen;
} varName1 ,..., varNamen;

Example

1
2
3
4
5
6
// Structure to handle complex numbers
struct complex
{
 float re;    
 float im;    
} x, y;        // Declare x and y of type complex

Back to Top

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

Back to Top

Using a Structure Variable

Syntax

structVariableName.memberName

Example

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 complex

int 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
...
}

Back to Top

Creating a Structure Type with typedef

Syntax

typedef struct structTagoptional
{
    type1 memberName1;
    ...
    typen memberNamen;
} typeName;

Example

1
2
3
4
5
6
// Structure type to handle complex numbers
typedef struct
{
 float re;    // Real part
 float im;    // Imaginary part
} complex;

Back to Top

Declaring a Structure Type Variable

Syntax

If typeName has already been defined:

typeName varName1 ,..., varNamen;

The keyword struct is no longer required!

Example

1
2
3
4
5
6
7
typedef struct
{
 float re;    
 float im;    
} complex;       
...
complex x, y;  // Declare x and y of type complex

Back to Top

Initializing a Structure Variable at Declaration

Syntax

If typeName or structName has already been defined:

typeName varName = {const1 ,..., constn};
  or  
struct structName varName = {const1 ,..., constn};

Example

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