Syntax to Define a Structure in C
We use struct keyword to define the structure. The syntax of a structure declaration in C is-
struct structure_name
{
datatype member1;
datatype member2;
.
.
datatype memberN;
};
In the above syntax, struct is a keyword, member1, member2, …….., memberN are members of the structure and are declared inside curly braces. These members can be of any data type like char, int, float, array, pointers, or another structure type.
Example
struct student
{
char name[20];
float marks;
int rollno;
};
In the above example, the structure named student has been defined, which contains three elements named name, marks, and rollno.
You can also read about the dynamic arrays in c and Short int in C Programming
Why Do We Use Structures in C?
Structures in C are used to group related data of different types under a single name, making it easier to manage and organize data. They provide several advantages, especially when working with complex data sets, such as records or entities that have multiple attributes. Below are the key reasons why we use structures in C:
- Grouping Related Data: Structures allow you to group different types of data that are logically related. For example, in a program dealing with students, you may want to store the student's name, age, and marks together, which can be efficiently done using a structure.
- Improving Code Organization: Using structures helps in organizing data more effectively, making your code more readable and maintainable. Instead of creating multiple individual variables for each piece of data (like name, age, and marks), you can encapsulate them into one structure, simplifying your code.
- Simplifying Complex Data Representation: In real-world applications, you often need to deal with more complex data models, like representing a book (with title, author, and price), or a product (with name, quantity, and price). Structures allow you to represent such complex entities clearly and concisely.
- Enabling Data Abstraction: Structures help in abstracting complex data structures, especially when working with databases or external systems. By grouping data together, structures enable easier manipulation, retrieval, and updates of records.
- Efficient Memory Usage: Structures help to save memory by grouping different data types together into one contiguous block of memory, making it easier to manage memory allocation. This is more memory-efficient than handling each variable separately.
- Supporting Arrays of Structures: In C, you can create arrays of structures, allowing you to handle a collection of related data efficiently. For instance, you could have an array of Student structures, each representing a student, and access each student's data using array indexing.
- Functionality for Larger Applications: Structures are crucial for more complex applications such as managing records, processing user input, creating data models for simulations, etc. They make it possible to design modular and scalable programs.
Declaring structure variables
We declare a variable for the structure to easily access the member of the structure. There are the following ways to declare structure variables:
- Using the structure tag
- With structure declaration
Using the structure tag
Here is an example of declaring the structure variables by struct keyword.
struct student
{
char name[20];
float marks;
int rollno;
};
struct student stu1, stu2, stu3; //declaring variables of struct Student
In the above example, stu1, stu2, and stu3 are structure variables that are declared using structure tag student.
With structure declaration
Here is another way to declare variables at the time of defining the structure.
struct student
{
char name[20];
float marks;
int roll_no;
}stu1, stu2, stu3;
In the above example, stu1, stu2, and stu3 are variables of type struct student. If the number of variables is not fixed, use the 1st approach; otherwise, use the 2nd approach.
Accessing Members of a Structure
There are two ways to access any member of a structure variable:
- Using . (dot operator)
- Using -> (structure pointer operator)
Generally, we use the member access operator (.) to access any member of a structure. The format for accessing a structure member is-
struct_variable.member
In the above syntax, on the left side of the dot operator, there should be a variable of structure type, and on the right side, there should be the name of a member of that structure.
For example
C
#include<stdio.h>
#include<string.h>
struct student
{
char name[20];
int rollno;
float marks;
};
int main()
{
struct student stu1;
stu1.rollno=12;
strcpy(stu1.name, "Dheeraj");
//displaying the stored values
printf("Name of student 1: %s\n", stu1.name);
printf("Roll number of student 1: %d\n", stu1.rollno);
return 0;
}
You can also try this code with Online C Compiler
Run Code
Output
Name of student 1: Dheeraj
Roll number of student 1: 12
In the above example, structure variable stu1 contains 'Dheeraj' for its first element name and 12 for its second element rollno.
Initialization of structure variables
The syntax of initializing structure variables is similar to that of arrays. We can use curly braces to assign initial values to a structure variable. The number, order, and type of these values should be the same as in the structure template definition.
Syntax:
struct <tagname><structvariable>={List of values};
Example
struct student
{
char name[20];
int rollno;
float marks;
};
struct student stu={"Dheeraj",12,78.9};
In the above example, structure variable stu1 has been initialized with values "Dheeraj", 12, and 78.9. "Dheeraj" would be stored in stu.name, and 12 would be stored in stu.rollno, and 78.9 would be stored in stu.marks.
Here is a C to Program to demonstrate the initialization of structure variables.
C
#include<stdio.h>
#include<string.h>
struct student
{
char name[20];
int rollno;
float marks;
};
int main()
{
struct student stu={"Dheeraj",12,78.9};
//displaying the stored values
printf("Name of student: %s\n", stu.name);
printf("Roll number of student: %d\n", stu.rollno);
return 0;
}
You can also try this code with Online C Compiler
Run Code
Output
Name of student: Dheeraj
Roll number of student: 12
Passing Structures to Functions in C
In C, structures can be passed to functions either by value or reference (by pointer). Each method has its own benefits and use cases. Let's break down both approaches:
1. Passing a Structure by Value
When you pass a structure by value to a function, the entire structure is copied to the function’s local variable. The function works with this copy, and any changes made to the structure inside the function do not affect the original structure in the calling function.
Syntax:
void function_name(struct StructureName variable_name) {
// Function code
}
Example: Passing Structure by Value
C
#include <stdio.h>
// Define a structure
struct Person {
char name[50];
int age;
};
// Function to display the structure's details
void displayPerson(struct Person p) {
printf("Name: %s\n", p.name);
printf("Age: %d\n", p.age);
}
// Main function
int main() {
struct Person person1 = {"Alice", 25};
// Passing structure to the function by value
displayPerson(person1); // Original structure remains unchanged
return 0;
}
You can also try this code with Online C Compiler
Run Code
Output:
Name: Alice
Age: 25
2. Passing a Structure by Reference (Pointer)
When you pass a structure by reference (using a pointer), you are passing the address (memory location) of the structure rather than a copy. This means that the function can directly modify the original structure.
Syntax:
void function_name(struct StructureName *variable_name) {
// Function code
}
Example: Passing Structure by Reference (Pointer)
C
#include <stdio.h>
// Define a structure
struct Person {
char name[50];
int age;
};
// Function to update age
void updateAge(struct Person *p) {
p->age = 30; // Modify the age of the original structure
}
// Main function
int main() {
struct Person person1 = {"Alice", 25};
// Passing structure to the function by reference (pointer)
updateAge(&person1); // Pass the address of person1
// Display the updated structure
printf("Updated Age: %d\n", person1.age);
return 0;
}
You can also try this code with Online C Compiler
Run Code
Output:
Updated Age: 30
Frequently Asked Questions
What is an array of structures?
Ans: An array of structures C programming is simply an array in which each element is a structure of the same type.
What is pointer to structure in C?
Ans: Pointer to structure holds the add of the entire structure. We use it to create complex data structures such as linked lists, trees, graphs, etc. The members of the structure can be accessed using a special operator called an arrow operator ( -> ).
Can we declare a function inside structure of C Programming?
Ans: No, We can not declare a function inside structure of C Programming.
Can we use access specifiers(private, public, protected) with structures?
Ans: Yes, We can use access specifiers(private, public, protected) with structures.
Conclusion
In this blog, We learned about structure. This blog also discussed the declaration of structure variables, accessing of a structure, and initialization of structure variables.
This blog is over, but the thirst for learning is not over yet. To understand the difference between classes and structure, click here. You can use our practice platform Code360 to practice various DSA questions asked in many interviews.
Check out this problem - Redundant Braces