C Programming Tutorial

C Programming Tutorial

Structure in C

Hello Everyone, In this article, we will explore the fundamental concept of structure in C programming. Structures provide a way to group different data types together under one name, allowing us to organize and manage related data more efficiently in our programs. Whether you are new to C or have some experience, this guide will help you to understand basics of structures in C effectively with examples. Let’s get started.

Definition of Structure

A structure in C programming is a user-defined data type that groups related variables of different data types under a single name. Structures are used to represent a record, making it easier to manage and access information. They help in organizing complex data by providing a convenient way to manage different types of data in a structured manner.

Syntax of Structure

The syntax for defining a structure is as follows:

struct structure_name {
    data_type member1;
    data_type member2;
    //...
    data_type memberN;
};

Where:

  • struct is a keyword used to define a structure.
  • structure_name is the name given to the structure.
  • data_type specifies the type of data for each member.
  • member1, member2, …, memberN are the names of the members (variables) inside the structure.

Here’s an example of a structure in C programming:

#include <stdio.h>// Defining a structure named 'Student'
struct Student {
    int id;
    char name[50];
    float percentage;
};

int main() {
    // Declare and initialize a variable of type 'Student'
    struct Student student1 = {1, "John Doe", 92.5};

    // Accessing members of the structure
    printf("Student ID: %d\\n", student1.id);
    printf("Student Name: %s\\n", student1.name);
    printf("Student Percentage: %.2f\\n", student1.percentage);

    return 0;
}

Output: The output for the above code will be:

Student ID: 1
Student Name: John Doe
Student Percentage: 92.50

In this example, we defined a structure named ‘Student’ with three members: id, name, and percentage. Then, we created a variable named ‘student1’ of type ‘Student’ and initialized it with values. Finally, we accessed the structure members using the dot operator (.) and printed them.

Defining and Declaring structure variable with Example.

Defining and declaring a structure variable involves two steps: first, you need to define the structure itself, and then declare a variable of that structure type. Here’s an example to illustrate these steps:

1. Define the structure: To define a structure, you need to use the struct keyword, followed by the structure name and its members enclosed in curly braces:

    struct Employee {
        int emp_id;
        char emp_name[50];
        float salary;
    };
    

    In this example, we’ve defined a structure named Employee with three members: emp_id, emp_name, and salary.

    2. Declare a structure variable: Once the structure is defined, you can declare a variable of that structure type using the structure name, followed by the variable name:

      struct Employee employee1;

      Here, we’ve declared a variable named employee1 of type Employee.

      Complete example:

      #include <stdio.h>
      #include <string.h>// Define the structure
      struct Employee {
          int emp_id;
          char emp_name[50];
          float salary;
      };
      
      int main() {
          // Declare and initialize a structure variable
          struct Employee employee1;
          employee1.emp_id = 101;
          strcpy(employee1.emp_name, "Jane Smith");
          employee1.salary = 50000.00;
      
          // Accessing members of the structure and printing their values
          printf("Employee ID: %d\\n", employee1.emp_id);
          printf("Employee Name: %s\\n", employee1.emp_name);
          printf("Employee Salary: %.2f\\n", employee1.salary);
      
          return 0;
      }
      

      Output:

      Employee ID: 101
      Employee Name: Jane Smith
      Employee Salary: 50000.00

      In this example, we defined a structure named Employee, declared a variable named employee1 of type Employee, and initialized its members. Then, we accessed the structure members using the dot operator (.) and printed their values.

      Structure in c programming with daily life example

      A structure in C programming can be compared to a real-life example of a school system. In a school, there are many entities, such as students, teachers, staff members, and classrooms. Each of these entities has its own set of attributes or properties. For instance, a student has a name, age, roll number, and class.

      Let’s use the student entity as an example to understand the concept of structures in C programming.

      1. Defining a structure: First, we need to define a structure to represent a student. We do this using the struct keyword, followed by the structure name and its members enclosed in curly braces:

        struct Student {
            int roll_number;
            char name[50];
            int age;
            char class[10];
        };
        

        In this example, we’ve defined a structure named Student with four members: roll_number, name, age, and class.

        2. Declaring a structure variable: Once the structure is defined, we can declare a variable of that structure type using the structure name, followed by the variable name:

          struct Student student1;

          Here, we’ve declared a variable named student1 of type Student.

          3. Initializing and accessing structure members: Now we can initialize the student1 structure variable with values and access its members using the dot operator (.):

            #include <stdio.h>
            #include <string.h>
            int main() {
                struct Student student1;
            
                // Initializing structure members
                student1.roll_number = 25;
                strcpy(student1.name, "John Doe");
                student1.age = 15;
                strcpy(student1.class, "10th Grade");
            
                // Accessing and printing structure members
                printf("Roll Number: %d\\n", student1.roll_number);
                printf("Name: %s\\n", student1.name);
                printf("Age: %d\\n", student1.age);
                printf("Class: %s\\n", student1.class);
            
                return 0;
            }
            

            Output:

            Roll Number: 25
            Name: John Doe
            Age: 15
            Class: 10th Grade
            

            In this daily life example, the Student structure represents an entity in a school system, and we used it to store and manage information about a specific student. Similarly, we can create other structures to represent teachers, staff members, and classrooms and use them to organize and manage data efficiently.

            Write the C program to Accessing Structure Members.

            In C programming, you can access structure members using the dot operator (.) after declaring and initializing a structure variable. Here’s an example to demonstrate this:

            #include <stdio.h>
            #include <string.h>// Define the structure
            struct Book {
                int book_id;
                char title[50];
                char author[50];
                float price;
            };
            
            int main() {
                // Declare and initialize a structure variable
                struct Book book1;
                book1.book_id = 1;
                strcpy(book1.title, "C Programming for Beginners");
                strcpy(book1.author, "John Smith");
                book1.price = 29.99;
            
                // Accessing and printing structure members
                printf("Book ID: %d\\n", book1.book_id);
                printf("Book Title: %s\\n", book1.title);
                printf("Book Author: %s\\n", book1.author);
                printf("Book Price: $%.2f\\n", book1.price);
            
                return 0;
            }
            

            In this example, we defined a structure named Book with four members: book_id, title, author, and price. We then declared a variable named book1 of type Book and initialized its members with values.

            To access the structure members, we used the dot operator (.) with the structure variable book1 followed by the member’s name. Finally, we printed the values of the structure members.

            Output:

            Book ID: 1
            Book Title: C Programming for Beginners
            Book Author: John Smith
            Book Price: $29.99

            This example demonstrates how to access structure members in a C program.

            Structures as Function Arguments in c programming

            In C programming, you can pass structures as function arguments just like any other data type. When you pass a structure to a function, a copy of the structure is created inside the function. This is known as passing by value. Any changes made to the structure inside the function do not affect the original structure in the calling function.

            Here’s an example to demonstrate passing structures as function arguments:

            #include <stdio.h>
            #include <string.h>// Define the structure
            struct Product {
                int product_id;
                char name[50];
                float price;
            };
            
            // Function prototype
            void display_product(struct Product p);
            
            int main() {
                // Declare and initialize a structure variable
                struct Product product1;
                product1.product_id = 101;
                strcpy(product1.name, "Wireless Mouse");
                product1.price = 25.99;
            
                // Pass the structure variable as an argument to the function
                display_product(product1);
            
                return 0;
            }
            
            // Function definition
            void display_product(struct Product p) {
                // Accessing and printing structure members
                printf("Product ID: %d\\n", p.product_id);
                printf("Product Name: %s\\n", p.name);
                printf("Product Price: $%.2f\\n", p.price);
            }
            

            In this example, we defined a structure named Product with three members: product_id, name, and price. We then declared a variable named product1 of type Product and initialized its members with values.

            We created a function called display_product() that takes a structure of type Product as an argument. Inside the function, we accessed the structure members and printed their values. Finally, we called the display_product() function from main() and passed the product1 structure variable as an argument.

            Output:

            Product ID: 101
            Product Name: Wireless Mouse
            Product Price: $25.99

            This example demonstrates how to pass structures as function arguments in C programming. Keep in mind that when passing structures to functions, a copy of the structure is created, and changes made inside the function do not affect the original structure.

            Pointers to structures in C programming are used to store the address of a structure variable, providing a way to access and manipulate the structure elements more efficiently. Using pointers to structures can help optimize memory usage, reduce code complexity, and improve performance.

            Here’s a basic example of defining a structure and using pointers to access its members:

            #include <stdio.h>// Define a structure called 'Person'
            typedef struct {
                char name[50];
                int age;
                float height;
            } Person;
            
            int main() {
                // Declare and initialize a 'Person' structure
                Person person1 = {"Alice", 30, 5.6};
            
                // Declare a pointer to the 'Person' structure
                Person *personPtr;
            
                // Point the pointer to the address of 'person1'
                personPtr = &person1;
            
                // Access and display the structure members using the pointer
                printf("Name: %s\\n", personPtr->name);
                printf("Age: %d\\n", personPtr->age);
                printf("Height: %.2f\\n", personPtr->height);
            
                return 0;
            }
            

            In this example, we define a structure called Person that contains three members: a name (a character array), an age (an integer), and a height (a float). We then declare a Person variable called person1 and initialize it with some values. We also declare a pointer to the Person structure called personPtr and point it to the address of person1.

            To access the structure members using the pointer, we use the ‘arrow operator’ (->).

            For example, personPtr->name is used to access the name member of the structure pointed to by personPtr.

            The output of the above code would be:

            Name: Alice
            Age: 30
            Height: 5.60
            
            Share This Article