How to Define and Declare Structs in C

This guide provides a clear overview of working with structures in the C programming language using the struct keyword. You will learn the fundamental difference between defining a structure layout and declaring structure variables, how to combine these processes, how to simplify syntax using typedef, and the basic methods for accessing structure members.

Understanding Structures in C

A structure in C is a user-defined composite data type that allows you to group variables of different data types under a single name. While arrays hold elements of the same type, structures can combine integers, floats, characters, pointers, and even other structures.

Defining a Structure

Defining a structure creates a blueprint or template; it specifies the data types and names of the members inside the structure without allocating any memory.

The basic syntax for a structure definition uses the struct keyword followed by an optional structure tag:

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

In this example, Person is the structure tag. It defines a new type called struct Person, containing three members: name, age, and height. Memory is not allocated until a variable of this type is declared.

Declaring Structure Variables

Once a structure type is defined, you can declare variables of that type to allocate memory.

1. Declaration After Definition

You can declare variables separately after defining the structure:

struct Person person1;
struct Person person2;

2. Declaration with Definition

You can declare variables immediately after the structure definition by placing variable names between the closing brace and the terminating semicolon:

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

3. Anonymous Structure Declaration

If you do not plan to reuse the structure blueprint elsewhere in your code, you can omit the tag:

struct {
    int x;
    int y;
} point1, point2;

Without a tag, no other variables of this exact type can be declared later.

Simplifying Declarations with typedef

In standard C, you must include the struct keyword every time you declare a variable (e.g., struct Person p;). To avoid this repetition, use the typedef keyword to create an alias:

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

Now, Person acts as a complete type name, allowing direct variable declarations:

Person person1;
Person person2;

Initializing and Accessing Members

To initialize a structure variable, provide values in braces matching the order of the defined members:

Person person1 = {"Alice", 30, 5.7};

To access or modify individual members, use the dot operator (.):

person1.age = 31;
printf("Name: %s, Age: %d\n", person1.name, person1.age);

If you are working with a pointer to a structure, use the arrow operator (->) instead of the dot operator:

Person *ptr = &person1;
ptr->age = 32;