Structures

Defining and using structures to group related data together. Accessing structure members using the dot operator.


C Structures

Defining Structures

In C programming, a structure is a user-defined data type that allows you to group together variables of different data types under a single name. Structures are useful for representing real-world entities that have multiple attributes. For example, a `student` could have attributes like `name`, `roll_number`, and `GPA`. Structures are essential for organizing complex data and creating more maintainable and readable code.

Syntax for Defining Structures (struct Keyword)

The struct keyword is used to define a structure in C. The general syntax is as follows:

 struct structure_name {
    data_type member1_name;
    data_type member2_name;
    ...
    data_type memberN_name;
}; 

Where:

  • struct: Keyword indicating a structure definition.
  • structure_name: The name you give to the structure. This is a type name, allowing you to declare variables of this structure type.
  • data_type: The data type of a member variable (e.g., int, float, char, etc.).
  • member1_name, member2_name, ...: The names of the member variables within the structure.

Declaring Structure Members and Their Data Types

Inside the structure definition, you declare the member variables and their corresponding data types. Each member represents an attribute of the structure.

Here's an example of a structure representing a point in 2D space:

 struct Point {
    int x;
    int y;
}; 

In this example:

  • struct Point defines a structure named Point.
  • int x; declares a member named x of type int, representing the x-coordinate.
  • int y; declares a member named y of type int, representing the y-coordinate.

Once the structure is defined, you can declare variables of that structure type. For example:

 struct Point p1, p2; // Declares two variables p1 and p2 of type struct Point
p1.x = 10;
p1.y = 20;
p2.x = 5;
p2.y = 8; 

This creates two variables, p1 and p2, each capable of holding the x and y coordinates of a point. The . (dot) operator is used to access the members of a structure variable.