In C, a structure is a user-defined data type that allows you to group together different data types under a single name. It enables you to create a more complex data type to represent a collection of related variables. Structures provide a way to organize and manage data, making the code more organized, readable, and maintainable.
Defining a Structure:
The syntax for defining a structure in C is as follows:
struct structName
{
dataType member1;
dataType member2;
// ... (more members)
};
- `structName`: This is the name of the structure, and you can use it to create variables of that structure type later.
- `dataType`: Each member inside the structure has its own data type.
For example, let's define a structure to represent a simple point with `x` and `y` coordinates:
struct Point
{
int x;
int y;
};
Creating Structure Variables:
Once you've defined a structure, you can create variables of that structure type, similar to creating variables of basic data types. The general syntax is:
struct structName variableName;
Using our previously defined `Point` structure:
struct Point p1; // Creates a variable 'p1' of type 'Point'
Accessing Structure Members:
To access the members (fields) of a structure variable, you use the dot (`.`) operator. For example, to set or retrieve the values of `x` and `y` for the `Point` structure:
p1.x = 10; // Set the value of 'x' in 'p1' to 10
p1.y = 20; // Set the value of 'y' in 'p1' to 20
printf("Coordinates: (%d, %d)\n", p1.x, p1.y); // Output: Coordinates: (10, 20)
Initializing Structure Variables:
You can initialize a structure variable at the time of declaration using curly braces `{}`:
struct Point p2 = { 30, 40 }; // Creates 'p2' and sets 'x' to 30 and 'y' to 40
You can also partially initialize a structure, leaving some members uninitialized:
struct Point p3 = { 50 }; // Creates 'p3' and sets 'x' to 50, 'y' remains uninitialized
Copying Structures:
When working with structures, it's important to understand how to copy structures. By default, when you assign one structure variable to another, a member-wise copy is performed. This means each member of the source structure is copied to the corresponding member in the destination structure.
For example:
struct Point
{
int x;
int y;
};
// Create structure variables
struct Point p1 = { 10, 20 };
struct Point p2;
// Perform structure copy
p2 = p1; // Member-wise copy from p1 to p2
printf("p2: (%d, %d)\n", p2.x, p2.y); // Output: p2: (10, 20)