Course Content
C Tutorial
About Lesson

Defining Structures

In the realm of C programming, structures serve as essential building blocks, allowing developers to create complex, custom data types. These structures enable the grouping of variables of different types under a single name, offering a more organized and efficient approach to handling data.

What Are Structures?

At its core, a structure in C is a composite data type that combines variables of various types under one declaration. Unlike arrays, which store elements of the same type, structures can hold different types of data simultaneously. This versatility makes them invaluable in managing diverse sets of information within a program.

Declaring and Defining Structures

To define a structure, one must specify its components using the struct keyword followed by a name that identifies the structure. For instance:

struct Person {
char name[50];
int age;
float height;
};

In this example, Person is the structure tag, and it contains variables representing a person’s name, age, and height. To create variables of this structure type, you can do so like this:

struct Person person1;
struct Person person2;

Accessing Structure Members

Accessing individual members within a structure involves using the dot (.) operator. For example:

strcpy(person1.name, "John Doe");
person1.age = 30;
person1.height = 175.5;

This snippet illustrates how to assign values to the person1 structure’s members.

Nested Structures

Structures can also be nested within one another, allowing for more complex data representations. Consider the following scenario:

struct Address {
char street[50];
char city[50];
int zipcode;
};

struct Employee {
char name[50];
struct Address address;
int employeeID;
};

Here, the Employee structure includes an Address structure as one of its members, enabling the encapsulation of address details within the employee’s data.

Benefits of Using Structures

Structures offer several advantages:

  1. Organized Data: Grouping related variables enhances code readability and organization.
  2. Custom Data Types: Structures allow the creation of user-defined data types tailored to specific requirements.
  3. Efficiency: Handling related data as a single unit can streamline operations and improve efficiency