Structures and Functions
Introduction
In C programming, one of the most powerful features is the ability to group different types of data into a single data type, which can be more conveniently handled and manipulated. This is done through 'Structures' and 'Unions'. In this tutorial, we will be focusing on 'Structures' and their interaction with 'Functions'.
Structures in C
A 'Structure' is a user-defined data type in C which allows you to combine data items of different kinds. Structures are used to represent a record, providing a more meaningful way of handling a group of related data.
Defining a Structure
You can define a structure using the struct
keyword. Here is an example of how to define a structure:
struct Student {
char name[50];
int roll;
float marks;
};
In the above code, Student
is a structure with three members: name
of type array, roll
of type integer, and marks
of type float.
Declaring Structure Variables
Once you've defined your structure, you can declare structure variables. Here's how:
struct Student s1, s2, s3;
In this case, s1
, s2
, and s3
are variables of the structure type Student
.
Accessing Structure Members
You can access the members of a structure using a dot (.
) operator. Here is an example:
strcpy(s1.name, "John");
s1.roll = 12;
s1.marks = 86.5;
Functions and Structures
Functions are blocks of code that perform specific tasks. You can pass structures as arguments to functions, just like any other data type.
Passing Structures to Functions
Here is an example of how you can pass a structure to a function:
void display(struct Student s) {
printf("Name: %s\n", s.name);
printf("Roll: %d\n", s.roll);
printf("Marks: %.2f\n", s.marks);
}
int main() {
struct Student s1;
strcpy(s1.name, "John");
s1.roll = 12;
s1.marks = 86.5;
display(s1); // Passing structure as an argument
return 0;
}
In this example, the structure s1
is passed to the function display
. The function then prints the members of the structure.
Conclusion
Structures provide a powerful way to group different types of data into a single data type. While this tutorial provided a basic overview of structures and how they interact with functions, keep practicing and experimenting with more complex uses to get a better understanding. Happy coding!