Passing structure to functions in c programming with example c tutorial
#Passing structure functions in c programming with example c language tutorial
In this guide, we’ll explore passing structure to function and compile and execution of it.
Passing structures to functions is a common practice in C programming, allowing efficient data handling. There are two primary methods to pass structures: pass by value and pass by reference. Understanding the differences between these methods helps in optimizing memory usage and function behavior.
In this guide, we'll explore how to pass a structure by value with a practical example.
When a structure is passed by value, a copy of the entire structure is made and sent to the function. Any modifications inside the function do not affect the original structure.
#include <stdio.h>
#include <string.h>
// Defining a Date structure
struct Date {
int day;
int month;
int year;
};
// Defining a Student structure with a nested Date structure
struct Student {
char name[50];
int age;
struct Date birthdate; // Nested structure
};
// Function to print Student details
void printStudent(struct Student p) {
printf("Name of student: %s\n", p.name);
printf("Age: %d\n", p.age);
printf("Birthdate: %d/%d/%d\n", p.birthdate.day, p.birthdate.month, p.birthdate.year);
}
int main() {
// Initializing a Student structure
struct Student person1;
strcpy(person1.name, "Developer Indian");
person1.age = 25;
// Assigning values to the nested structure
person1.birthdate.day = 15;
person1.birthdate.month = 7;
person1.birthdate.year = 1998;
// Calling the function and passing the structure by value
printStudent(person1);
return 0;
}
When you pass a structure by value, a new copy is created, and modifications within the function do not alter the original structure. This approach is useful when you need to ensure data integrity and avoid accidental modifications. However, if you want the function to modify the original structure, you should use pass by reference with pointers