Method 1: Pass by Value:
- The structure is copied into the function. Changes made inside the function do not affect the original.
void display(struct Student s) {
printf("ID: %d, Name: %s, Marks: %.2f\n", s.id, s.name, s.marks);
}Method 2: Pass by Reference (Using Pointers):
- The function receives the address of the structure. Any changes made reflect outside the function.
void updateMarks(struct Student *s) {
s->marks += 5.0; // Increment marks by 5
}Passing Structure to Function Full Example:
Thank you for reading this post, don't forget to subscribe!#include <stdio.h>
#include <string.h>
struct Student {
int id;
char name[50];
float marks;
};
void display(struct Student s) {
printf("ID: %d, Name: %s, Marks: %.2f\n", s.id, s.name, s.marks);
}
void updateMarks(struct Student *s) {
s->marks += 5.0;
}
int main() {
struct Student st = {1, "Alice", 80.0};
display(st); // Pass by value
updateMarks(&st); // Pass by reference
display(st); // Updated marks
return 0;
}Passing Array of Structures to Function:
Syntax:
void displayAll(struct Student arr[], int size);Example:
#include <stdio.h>
struct Student {
int id;
char name[50];
float marks;
};
void displayAll(struct Student arr[], int size) {
for (int i = 0; i < size; i++) {
printf("ID: %d, Name: %s, Marks: %.2f\n",
arr[i].id, arr[i].name, arr[i].marks);
}
}
int main() {
struct Student students[2] = {
{101, "John", 88.5},
{102, "Emma", 91.0}
};
displayAll(students, 2);
return 0;
}