Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Introduction to Structures in C

What is a Structure?

In C, a structure is a user-defined data type that allows you to combine data items of different kinds. Structures are used to represent a record, suppose you want to keep track of books in a library. You might want to track the following attributes about each book:

  • Title
  • Author
  • Subject
  • Book ID

Defining a structure in C allows you to create a single data type that can hold these different kinds of data under one name.

Defining a Structure

The struct keyword is used to define a structure in C. Here is the general syntax:

struct [structure name] {
    data_type member1;
    data_type member2;
    ...
    data_type memberN;
};

For example, let's define a structure Book:

struct Book {
    char title[50];
    char author[50];
    char subject[100];
    int book_id;
};

Declaring Structure Variables

Once a structure is defined, you can declare variables of that type. Here is how you can declare a variable of the Book structure:

struct Book myBook;

You can also initialize the structure at the time of declaration:

struct Book myBook = {"The C Programming Language", "Brian W. Kernighan and Dennis M. Ritchie", "Programming", 1001};

Accessing Structure Members

To access members of a structure, use the dot operator (.). For example:

myBook.title

You can assign values to members of the structure like this:

struct Book myBook;
myBook.book_id = 1001;

And you can print the values of members like this:

printf("Book ID: %d", myBook.book_id);

Example Program

Below is a complete example program that demonstrates the use of structures:

#include <stdio.h>
#include <string.h>

struct Book {
    char title[50];
    char author[50];
    char subject[100];
    int book_id;
};

int main() {
    struct Book book1;

    // Assign values to book1
    strcpy(book1.title, "The C Programming Language");
    strcpy(book1.author, "Brian W. Kernighan and Dennis M. Ritchie");
    strcpy(book1.subject, "Programming");
    book1.book_id = 1001;

    // Print book1 info
    printf("Book 1 title: %s\n", book1.title);
    printf("Book 1 author: %s\n", book1.author);
    printf("Book 1 subject: %s\n", book1.subject);
    printf("Book 1 book_id: %d\n", book1.book_id);

    return 0;
}
Book 1 title: The C Programming Language
Book 1 author: Brian W. Kernighan and Dennis M. Ritchie
Book 1 subject: Programming
Book 1 book_id: 1001

Conclusion

In this tutorial, we covered the basics of structures in C. You learned what a structure is, how to define and declare structures, and how to access their members. Structures are a powerful feature in C that allows you to group different types of data together, making your programs more organized and easier to manage.