Structure in C

SPONSOR AD

Structure in C with Examples

In this article, I will discuss the Structure in C Language with Examples. Please read our previous article discussing Error Handling in C Programs. You will understand the following pointers in detail at the end of this article.

  1. What is Structure in C?
  2. How is Memory Created for a Structure in C?
  3. How do you Declare a Variable of Type Structure?
  4. Where is the Structure Variable Created Inside the Main Memory?
  5. How to Access the Members of a Structure in C?
  6. Real-Time Examples to Understand Structure
  7. Advantages and Disadvantages of Using Structure in C?
  8. When to Use Structure in C Language?
What is Structure in C?

The structure can be defined as a collection of related data members under one name. Those data members may be of similar type or may be of dissimilar type. So, usually, it is defined as a collection of dissimilar data items under one name. In C programming, a structure (often referred to as a struct) is a user-defined data type that allows you to combine data items of different kinds. Structures are used to represent a record. 

Structure in C is used for defining user-defined data types. Apart from the primitive data type we have in any programming language, for example, in C language, we have primitive data types such as integer, float, double, etc. Using these primitive data types. We can also define our own data type depending on our own requirements. And this is possible in C because of Structure.

In this course, I am going to use Structure more frequently. In this article, we will learn how to define the structure and what it means by the size of a structure, like how much memory it consumes. Then, we will discuss how to declare a structure and how to access the members of a structure.

SPONSOR AD
Example to Understand Structure in C Language:

Let us take an example of a rectangle. As shown in the image below, a rectangular figure has two properties, i.e., length and breadth.

Example to understand Structure

So, a rectangle will have length and breadth, which means these two things (length and breadth) together define a rectangle. So, in your programs, if you need something like a rectangle, then you need to define a structure for it because a rectangle is not defined by just one value but rather is defined by a set of related values, i.e., length and breadth. So, you can group them together under one name and define it as a structure.

To define a structure, you must use the struct statement. The struct statement defines a new data type with more than one member for your program. For example, you need to define a structure for a rectangle, as shown below.

What is Structure in C?

As shown in the above image, we are creating a struct Rectangle. Inside this, we have an integer type length and an integer type breadth. Now, this struct rectangle has two members (length and breadth).

We take length and breadth as an integer type, but you can also take them as float double or any other type, depending on your business requirement. So, a structure rectangle is defined by its length and breadth, or we can say these two data members define a rectangle together. This is the definition of a structure.

SPONSOR AD
How Much Memory this Rectangle Will Consume?

It has two integer members. Integer takes 2 bytes, or it may take 4 bytes, depending upon the Operating system and compiler. But let’s assume it takes 2 bytes. So, it will take a total of 4 bytes (2 bytes for length plus 2 bytes for breadth) of memory.

So, this rectangle structure is taking 4 bytes of memory. Right now, it is not consuming any memory because it is just a definition. So, if we create a variable of this type, it will occupy that much memory. So, the size of a structure is the total amount of memory consumed by all its members.

How to Declare a Variable of Type Structure in C?

Please have a look at the below code.

How to declare a variable of type structure?

As you can see in the above code, we declare a variable inside the main() method. So, the method of structure variable declaration is writing struct as a keyword, then giving the structure name, i.e., Rectangle, and followed by the variable name, i.e., in this case, ‘r’. This is the declaration of a structure variable. Now, this r will occupy the memory space and be created in the memory. We can also declare and initialize simultaneously, as shown below.

How much memory this rectangle will be consuming?

As you can see in the above image, the struct variable r is created with the values 10 and 5. Here, the value 10 is assigned to length, and the value 5 is assigned to breadth.

Where Is This r Variable Created Inside the Main Memory?

The variable r will be created inside the stack frame of the main memory, as shown in the image below.

SPONSOR AD

Where this r variable is created inside the Main memory?

How Do I Access the Members of a Structure in C?

We use the member access operator (.) to access any structure member. Member access operator is coded as a period between the structure variable name and the structure member we wish to access. Suppose you want to access the structure’s length, i.e., modify the length value to 15. To access a structure member, we need to use the structure variable name and the dot operator followed by the structure member name. The following statement shows how to modify the length of the structure.

r.length=5

What Is the Operator Used For Accessing the Member of a Structure in C Language?

The dot (.) operator is used for accessing a structure member. So, if you want to read and write the members of a structure, then you need to use the dot operator. Let us write the complete example, which will calculate the area of a rectangle using structure in c language.

#include <stdio.h>
struct Rectangle
{
    int length;
    int breadth;
};

int main()
{
    struct Rectangle r = { 10, 5 };
    r.length = 20;
    r.breadth = 10;
    printf ("Area of Rectangle: %d", r.length * r.breadth);
    return 0;
}

Output: Area of Rectangle: 200

Structure Real-time Examples in C Language:

Structures in C are a powerful way to group related data together. Let’s look at some real-world examples where structures can be used effectively:

Example: Student Record System

In a student record system, a structure can be used to hold information about each student, such as their name, ID, and grades.

#include <stdio.h>

struct Student {
    int id;
    char name[50];
    float grade;
};

int main() {
    struct Student student1;

    student1.id = 1;
    strcpy(student1.name, "Alice");
    student1.grade = 3.5;

    printf("Student ID: %d\n", student1.id);
    printf("Student Name: %s\n", student1.name);
    printf("Student Grade: %.1f\n", student1.grade);

    return 0;
}
Example: Inventory Management

In an inventory management system, a structure can represent items in the inventory with fields like item ID, name, and quantity.

#include <stdio.h>

struct InventoryItem {
    int itemId;
    char itemName[100];
    int quantity;
};

int main() {
    struct InventoryItem item;

    item.itemId = 101;
    strcpy(item.itemName, "Laptop");
    item.quantity = 50;

    printf("Item ID: %d\n", item.itemId);
    printf("Item Name: %s\n", item.itemName);
    printf("Quantity: %d\n", item.quantity);

    return 0;
}
Example: Employee Management

A structure can hold details like employee ID, name, and salary for managing employee data.

#include <stdio.h>

struct Employee {
    int empId;
    char empName[50];
    float salary;
};

int main() {
    struct Employee emp;

    emp.empId = 123;
    strcpy(emp.empName, "Bob");
    emp.salary = 55000.00;

    printf("Employee ID: %d\n", emp.empId);
    printf("Employee Name: %s\n", emp.empName);
    printf("Salary: %.2f\n", emp.salary);

    return 0;
}
Example: Book Management

Suppose you want to keep track of books in a library. You might want to track the following attributes of each book:

SPONSOR AD
  • Title
  • Author
  • Subject
  • Book ID

The complete example code is given below:

#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;        /* Declare Book1 of type Book */
   struct Book Book2;        /* Declare Book2 of type Book */
 
   /* book 1 specification */
   strcpy(Book1.title, "C Programming");
   strcpy(Book1.author, "Nuha Ali"); 
   strcpy(Book1.subject, "C Programming Tutorial");
   Book1.book_id = 6495407;

   /* book 2 specification */
   strcpy(Book2.title, "Telecom Billing");
   strcpy(Book2.author, "Zara Ali");
   strcpy(Book2.subject, "Telecom Billing Tutorial");
   Book2.book_id = 6495700;
 
   /* 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);

   /* print Book2 info */
   printf("Book 2 title : %s\n", Book2.title);
   printf("Book 2 author : %s\n", Book2.author);
   printf("Book 2 subject : %s\n", Book2.subject);
   printf("Book 2 book_id : %d\n", Book2.book_id);

   return 0;
}

In this example, Book1 and Book2 are two variables of type Book, meaning they can store information about two books. The details of each book, like title, author, and subject, are stored in these variables and then printed out.

Bank Account Management

For managing bank accounts, structures can be used to hold account details:

#include <stdio.h>

typedef struct {
    int accountNumber;
    char accountHolder[100];
    double balance;
} BankAccount;

void showAccount(BankAccount acc) {
    printf("Account Number: %d, Holder: %s, Balance: %.2lf\n", acc.accountNumber, acc.accountHolder, acc.balance);
}

int main() {
    BankAccount account1 = {123456, "Jane Roe", 2000.00};
    showAccount(account1);
    return 0;
}

These examples demonstrate the use of structures to encapsulate and manage related data in various applications. Structures make the code more organized and readable, particularly when dealing with complex data.

Advantages and Disadvantages of Using Structure in C Language:

Using structures in C language offers several advantages but also comes with certain drawbacks. Here’s a breakdown of the pros and cons:

Advantages of Using Structures in C Language
  • Data Organization: Structures help organize complex data logically by allowing different data types to be grouped under a single entity.
  • Code Readability and Maintenance: Code that uses structures is often more readable and easier to maintain since structures clearly represent real-world entities.
  • Ease of Handling: Structures make handling and manipulating data easier as they allow passing multiple attributes as a single argument to functions.
  • Facilitates Modular Programming: Using structures can make the program more modular, as you can create functions that operate on the structure as a whole.
  • Reduces Complexity: Structures can reduce the complexity of handling numerous data variables, especially in large programs by encapsulating related data.
  • Memory Efficient: Structures can be more memory efficient than separate arrays or variables for each piece of data, especially when arrays of structures are used.
  • Foundation for OOP: Structures lay the groundwork for more advanced programming concepts, such as object-oriented programming (in languages like C++).
Disadvantages of Using Structures in C Language:
  • No Data Hiding: Structures in C do not support data hiding. All structure members are by default public, and there are no access specifiers like private or protected, as in OOP languages.
  • No Member Functions: C structures cannot have functions as members. They are purely a data-holding entity.
  • Limited Functionality: Structures do not support constructors, destructors, or methods that automatically initialize or clean up resources, which can lead to manual error-prone handling.
  • Memory Alignment: Structures may use more memory than necessary due to padding added by the compiler for alignment purposes.
  • Deep Copy Complexity: When a structure contains pointers to dynamically allocated memory, deep copying (replicating both the structure and the memory pointed to by its pointers) can be complex and error-prone.
  • No Inheritance or Polymorphism: Structures do not support key object-oriented features like inheritance and polymorphism, limiting the ability to create more abstract and flexible data models.
  • Function Overhead: Passing large structures to functions (if passed by value) can be inefficient as it involves copying the entire structure.
When to Use Structure in C Language?

Structures in C are a versatile and powerful feature, often used when you need to group related data items of different types. Understanding when to use structures can greatly enhance your program’s design and readability. Here are some typical scenarios where structures are beneficial:

  • Grouping Related Data: When you have related data items that logically belong together, a structure can group them into a single unit. For example, a structure can group an employee’s name, ID, and salary if you manage employee data.
  • Complex Data Handling: Structures are ideal for handling complex data that involves multiple attributes. For instance, in a graphics program, a structure can represent a point with x, y, and z coordinates.
  • Database Records: Structures are useful for representing records in a makeshift database, where each structure instance can represent a row in the database.
  • Implementing Abstract Data Types: Structures are often used in implementing abstract data types (ADTs) like stacks, queues, linked lists, trees, graphs, etc. These ADTs involve grouping data with its related operations.
  • Passing Multiple Arguments to Functions: You can use structures to pass multiple data items to a function in a neat package, especially when the data items are related. This makes the function calls cleaner and the function definitions more manageable.
  • Returning Multiple Values from Functions: Structures enable functions to return multiple values. This can be an elegant solution when a function must provide various related information.
  • Cross-Functional Data Usage: When the same data needs to be accessed and used by multiple functions, passing a structure can be more efficient than passing individual data items.

In the next article, I will discuss Self-Referential Structure in C Language with Example. In this article, I try to explain Structure in C with Examples. I hope you enjoy this Structure in C with Examples article. I would like to have your feedback. Please post your feedback, questions, or comments about this Structure in C with Examples article.

SPONSOR AD

Leave a Reply

Your email address will not be published. Required fields are marked *