Structure in C Programming





Structure is a user defined data type which can hold different type of data in a single unit. Structure is represented by struct keyword.


A structure is defined using the struct keyword, followed by the name of the structure and a set of curly braces {} that enclose the variables or members within it. Each member has a name and a data type, and they are separated by semicolons.


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

In the above example, we have defined a structure called Person with three members: name of type char array, age of type int, and height of type float.

Once a structure is defined, you can create variables of that structure type, just like any other data type. For example:


    struct Person person1;
  

You can access the members of a structure using the dot . operator. For instance, to assign values to the members of person1:


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

You can also declare a structure variable and initialize it at the same time:


    struct Person person2 = {"Jane Smith", 30, 160.0};
  

Structures allow you to organize related data into a single entity, making it easier to manage and manipulate data as a unit. They are often used to represent real-world entities or complex data structures in programming.



Important Points about Structures in C Programming


  • Structure Declaration: Structures are declared using the struct keyword, followed by the structure name and a set of curly braces {} that enclose the members.
  • Structure Members: Members within a structure can have different data types, such as int, char, float, arrays, or even other structures. Each member is separated by a semicolon.
  • Accessing Structure Members: You can access structure members using the dot . operator. For example, structureName.memberName.
  • Structure Variables: After declaring a structure, you can create variables of that structure type just like any other data type. For example, struct Person person1;.
  • Initialization: Structure variables can be declared and initialized at the same time using curly braces {}. For example, struct Person person2 = {"Jane Smith", 30, 160.0};.
  • Structure Size: The size of a structure is determined by the sum of the sizes of its members. It may be larger than the sum of its individual members due to padding added by the compiler for alignment purposes.
  • Passing Structures to Functions: Structures can be passed as function arguments by value or by reference (using pointers). By default, C uses a "pass by value" mechanism.
  • Nested Structures: Structures can be nested within each other, allowing you to create complex data structures.
  • Typedef: You can use the typedef keyword to create a new name (alias) for a structure, which can simplify the declaration of structure variables.
  • Arrays of Structures: You can create arrays of structures to store multiple instances of the same structure type.
  • File Operations: Structures can be used to read and write data from files, making it easier to handle structured data stored in external files.


Here's an example that demonstrates assigning values to structure elements during structure creation:

#include <stdio.h>

struct Point {
    int x;
    int y;
};

int main() {
    struct Point p1 = {10, 20};

    // Accessing structure elements
    printf("Point p1: x = %d, y = %d\n", p1.x, p1.y);

    return 0;
}
Output:
Point p1: x = 10, y = 20

In the above code, the structure Point is defined with x and y as its elements. The variable p1 of type struct Point is declared and initialized with the values 10 and 20, respectively, at the time of creation. The values of the structure elements are accessed and printed using the printf function.



Here's an example that demonstrates assigning values to structure elements:

#include <stdio.h>

struct Point {
    int x;
    int y;
};

int main() {
    struct Point p1;

    // Assigning values to structure elements
    p1.x = 10;
    p1.y = 20;

    // Accessing structure elements
    printf("Point p1: x = %d, y = %d\n", p1.x, p1.y);

    return 0;
}

 
Point p1: x = 10, y = 20

In the above code, a structure Point is defined with x and y as its elements. The variable p1 of type struct Point is declared, and then the values 10 and 20 are assigned to its x and y elements, respectively. The values of the structure elements are accessed and printed using the printf function.

Here we have one more way of declaration of a structure at the time of creation.

struct Point {
    int x;
    int y;
} p1 = {10, 20};

int main() {
    // Accessing structure members
    printf("Point p1: x = %d, y = %d\n", p1.x, p1.y);
    
    return 0;
}
Output:
Point p1: x = 10, y = 20

Here we have an example which can store the information for a book?

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

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

int main() {
   struct Book book1;        // Declare book1 of type Book
   struct Book book2;        // Declare book2 of type Book

   strcpy(book1.title, "C Programming");
   strcpy(book1.author, "Anil Kumar");
   strcpy(book1.subject, "C Language");
   book1.book_id = 6495407;

   // Book 2 specification
   strcpy(book2.title, "Java");
   strcpy(book2.author, "Mukesh Yadav");
   strcpy(book2.subject, "Java Language");
   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\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;
}
output:
Book 1 title: C Programming
Book 1 author: Anil Kumar
Book 1 subject: C Language
Book 1 book_id: 6495407

Book 2 title: Java
Book 2 author: Mukesh Yadav
Book 2 subject: Java Language
Book 2 book_id: 6495700

The code includes two header files stdio.h for input/output operations and string.h for string manipulation functions. It defines a structure called Book that represents a book. The structure has four members title, author, subject, and book_id.

The main() function is the starting point of the program. Inside the main() function, two variables of type struct Book are declared: book1 and book2. These variables will hold the information for two books. Information about the first book, book1, is assigned using the strcpy() function. The strcpy() function is used to copy strings from one variable to another. The title, author, subject, and book_id of book1 are set to specific values.

Information about the second book, book2, is assigned in a similar manner. The program then proceeds to print the information of book1 and book2 using printf() statements. The %s format specifier is used to print strings, and the %d format specifier is used to print integers. Finally, the program ends with the return 0 statement, indicating successful execution.



One more structure example which will collect the Employee Information and display.

#include <stdio.h>

struct Employee {
    int employeeID;
    char name[50];
    int age;
    char department[50];
};

int main() {
    struct Employee emp;

    printf("Enter employee ID: ");
    scanf("%d", &emp.employeeID);

    printf("Enter employee name: ");
    scanf("%s", emp.name);

    printf("Enter employee age: ");
    scanf("%d", &emp.age);

    printf("Enter employee department: ");
    scanf("%s", emp.department);

    printf("\nEmployee Information\n");
    printf("ID: %d\n", emp.employeeID);
    printf("Name: %s\n", emp.name);
    printf("Age: %d\n", emp.age);
    printf("Department: %s\n", emp.department);

    return 0;
}

Output:
Enter employee ID: 101
Enter employee name: Ram
Enter employee age: 34
Enter employee department: Teacher

Employee Information
ID: 101
Name: Ram
Age: 34
Department: Teacher

This program is designed to collect and display information about employees. It uses a structure called Employee to represent an employee's data, including their ID, name, age, and department.

The program starts by declaring the necessary header file stdio.h for input and output operations. Then, the Employee structure is defined, which consists of four fields: employeeID (an integer), name (a character array of size 50), age (an integer), and department (a character array of size 50).

In the main() function, a variable emp of type Employee is created to store the information of a single employee. The program prompts the user to enter the employee's ID, name, age, and department using printf and scanf functions. The entered values are then stored in the corresponding fields of the emp structure.

After collecting the employee information, the program displays it on the console using printf statements. The employee's ID, name, age, and department are printed one by one.

Finally, the program returns 0, indicating successful execution.


Structure which can hold n number of students record.

#include<stdio.h>
struct Student  // Global Structure declaration
{
int roll;
char name[45];
int marks[6]; // will hold six subjects marks
};
	  
int main()
{
// Declaration of a structure
struct Student s[50]; // this structure can hold MAX 50 student record.
int size,i;
printf("Enter the size of an array :\n");
scanf("%d",&size);
for(i=0;i<size;i++)
{
printf("Enter the Record of %d student :\n\n",i+1);
printf("Enter Roll :\n");
scanf("%d",&s[i].roll);
printf("Enter the name of the student :\n");
scanf("%s",s[i].name);
printf("Enter Marks :\n");
printf("For Hindi :\n");
scanf("%d",&s[i].marks[0]);
printf("For English :\n");
scanf("%d",&s[i].marks[1]);
printf("For Math :\n");
scanf("%d",&s[i].marks[2]);
printf("For Science :\n");
scanf("%d",&s[i].marks[3]);
printf("For SS :\n");
scanf("%d",&s[i].marks[4]);
printf("For ICT :\n");
scanf("%d",&s[i].marks[5]);
}
printf("\nThe output is :\n\n");
for(i=0;i<size;i++)
{
printf("Record of %d student :\n\n",i+1);
printf("Roll : %d\n",s[i].roll);
printf("Name : %s\n",s[i].name);
printf("For Hindi : %d\n",s[i].marks[0]);
printf("For English :%d\n",s[i].marks[1]);
printf("For Math :%d\n",s[i].marks[2]);
printf("For Science :%d\n",s[i].marks[3]);
printf("For SS :%d\n",s[i].marks[4]);
printf("For ICT :%d\n",s[i].marks[5]);
}
}
output:
Enter the size of an array :
2
Enter the Record of 1 student :

Enter Roll :
101
Enter the name of the student :
Ram
Enter Marks :
For Hindi :
90
For English :
95
For Math :
99
For Science :
87
For SS :
97
For ICT :
88
Enter the Record of 2 student :

Enter Roll :
102
Enter the name of the student :
Mohan
Enter Marks :
For Hindi :
98
For English :
89
For Math :
95
For Science :
69
For SS :
94
For ICT :
99

The output is :

Record of 1 student :

Roll : 101
Name : Ram
For Hindi : 90
For English :95
For Math :99
For Science :87
For SS :97
For ICT :88
Record of 2 student :

Roll : 102
Name : Mohan
For Hindi : 98
For English :89
For Math :95
For Science :69
For SS :94
For ICT :99

This code allows the user to input and store information about students using a structure called Student. The structure has three members: roll (integer), name (character array), and marks (integer array to hold marks for six subjects).

Inside the main() function, an array of structures s is declared, which can hold a maximum of 50 student records. The size of the array is determined by user input. The user is prompted to enter the size of the array, which represents the number of students' records they want to input.

A for loop is used to iterate through each element of the array and gather the student information. For each student, the program prompts the user to enter the student's roll number, name, and marks for six subjects (Hindi, English, Math, Science, Social Science, and ICT). The input is stored in the respective members of the Student structure.

After gathering all the student information, the program proceeds to display the output. Another for loop is used to iterate through each student record in the array. For each student, the program displays the roll number, name, and marks for all six subjects. The program execution completes, and the output is shown on the console.



Pass the structure with in function argument [Call by value].

#include <stdio.h>

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

// Function that takes a structure as an argument
void displayBook(struct Book book) {
   printf("Title: %s\n", book.title);
   printf("Author: %s\n", book.author);
   printf("Subject: %s\n", book.subject);
   printf("Book ID: %d\n", book.book_id);
}

int main() {
   struct Book myBook;

   // Assign values to the structure members
   strcpy(myBook.title, "C Programming");
   strcpy(myBook.author, "Anil Kumar");
   strcpy(myBook.subject, "C Language");
   myBook.book_id = 6495407;

   // Call the function and pass the structure as an argument
   displayBook(myBook);

   return 0;
}

output:
Title: C Programming
Author: Anil Kumar
Subject: C Language
Book ID: 6495407

In this example, we have a structure Book with various members. The displayBook() function is defined to take a Book structure as an argument. Inside the function, the values of the structure members are accessed and printed.

In the main() function, a Book structure named myBook is declared. Values are assigned to its members. Then, the displayBook() function is called and myBook is passed as an argument.

When the displayBook() function is called, the structure passed as an argument is accessed within the function, and its members are printed.

Note that when passing structures as function arguments, a copy of the structure is made. If you modify the structure within the function, the changes will not affect the original structure in the calling function. If you want to modify the original structure, you can pass a pointer to the structure as an argument instead.



Pass a structure as a reference to a function argument [Call by reference]

In C, you can pass a structure as a reference to a function argument by using pointers. Pointers allow you to directly manipulate the original structure within a function. Here's an example:

#include <stdio.h>

struct Person {
    char name[20];
    int age;
};

void modify_struct(struct Person* person) {
    strcpy(person->name, "John");
    person->age = 30;
}

int main() {
    struct Person person;
    strcpy(person.name, "Alice");
    person.age = 25;
    
    printf("Before: %s, %d\n", person.name, person.age);

    modify_struct(&person);
    
    printf("After: %s, %d\n", person.name, person.age);
    
    return 0;
}

output:
Before: Alice, 25
After: John, 30

In this example, we define a structure Person with two members: name and age. The function modify_struct takes a pointer to a Person structure as an argument. Within the function, we can use the -> operator to access and modify the structure members directly.

In the main function, we create a Person variable named person and initialize its values. We then pass a pointer to the person structure using the & operator to the modify_struct function. Any changes made to the structure within the modify_struct function will affect the original person structure.

Note that in C, you need to include the appropriate header files, such as , and use functions like strcpy to manipulate strings.

Discribe a nested structure in c programming language

In C, a nested structure is a structure that is defined within another structure. It allows you to create more complex data structures by combining multiple structures together.

In C, a nested structure is a structure that is defined within another structure. It allows you to create more complex data structures by combining multiple structures together. Here's an example of a nested structure:

#include 

struct Date {
    int day;
    int month;
    int year;
};

struct Person {
    char name[20];
    int age;
    struct Date birthdate;
};

int main() {
    struct Person person;
    strcpy(person.name, "Alice");
    person.age = 25;
    person.birthdate.day = 15;
    person.birthdate.month = 6;
    person.birthdate.year = 1998;
    
    printf("Name: %s\n", person.name);
    printf("Age: %d\n", person.age);
    printf("Birthdate: %d/%d/%d\n", person.birthdate.day, person.birthdate.month, person.birthdate.year);
    
    return 0;
}
Name: Alice
Age: 25
Birthdate: 15/6/1998

In this example, we have two structures: Date and Person. The Date structure represents a date with day, month, and year members. The Person structure represents a person with name, age, and birthdate members. The birthdate member of the Person structure is of type Date, making it a nested structure.

In the main function, we create a Person variable named person and initialize its values. We can access the nested structure members using the dot (.) operator. For example, to set the birthdate values, we use person.birthdate.day, person.birthdate.month, and person.birthdate.year.

Nested structures allow you to organize and access related data in a hierarchical manner, making it easier to represent complex entities in your programs.



typedef in C - Structures


In C programming, the typedef keyword is used to create a new type alias. It can also be used to provide a new name for a structure, making it more convenient to use throughout the code.

Here's an example:


#include <stdio.h>

typedef struct {
    int id;
    char name[20];
    int age;
} Person;

int main() {
    Person p1;

    p1.id = 1;
    strcpy(p1.name, "John");
    p1.age = 25;

    printf("Person Details:\n");
    printf("ID: %d\n", p1.id);
    printf("Name: %s\n", p1.name);
    printf("Age: %d\n", p1.age);

    return 0;
}
    

In this example, we use typedef to create a new type alias called Person for the structure. This allows us to declare variables of the renamed structure type as Person p1; instead of struct Person p1;. The code then assigns values to the structure members and prints the person's details using printf().

By using typedef, we can refer to the structure as Person instead of struct Person, making the code more readable and concise.



Here's is another example how you can use typedef to rename a structure: Find the original structure declaration in your code:

    
struct MyStructure { // Structure members };
Use typedef followed by the original structure declaration to create a new type alias:
typedef struct MyStructure NewName;
From now on, you can use NewName as a shorthand for struct MyStructure when declaring variables or using the structure:
NewName example; // Declare a variable of the renamed structure type example.member = 42; // Access structure members using the new name

By using typedef, you create a new type alias NewName for the structure struct MyStructure. This allows you to use the NewName identifier instead of the full struct MyStructure throughout your code, making it more concise and readable.

It's worth noting that the typedef declaration should be placed outside of any function blocks, typically at the global level, to ensure the type alias is visible throughout your codebase.