Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to pass the individual members as arguments to function using structure elements?
In C programming, there are three ways to pass structure data to functions. One of the most basic approaches is passing individual structure members as separate arguments to a function. This method treats each structure member as an independent variable in the function call.
Syntax
// Function declaration returnType functionName(dataType1 member1, dataType2 member2, ...); // Function call functionName(structVariable.member1, structVariable.member2, ...);
How It Works
- Each member is passed as a separate argument in the function call
- Members are collected independently as ordinary variables in the function parameters
- Changes made to parameters inside the function do not affect the original structure members
Example 1: Basic Date Structure
Here is a simple example demonstrating how to pass individual structure members to a function −
#include <stdio.h>
struct date {
int day;
int month;
int year;
};
void display(int d, int m, int y) {
printf("Day = %d
", d);
printf("Month = %d
", m);
printf("Year = %d
", y);
}
int main() {
struct date d = {15, 8, 2024};
// Passing individual members as arguments
display(d.day, d.month, d.year);
return 0;
}
Day = 15 Month = 8 Year = 2024
Example 2: Student Record Structure
This example shows a more complex structure with different data types being passed individually −
#include <stdio.h>
#include <string.h>
struct student {
int id;
char name[20];
float percentage;
};
void displayStudent(int id, char name[], float percentage) {
printf("Student ID: %d
", id);
printf("Student Name: %s
", name);
printf("Percentage: %.2f%%
", percentage);
}
int main() {
struct student record;
record.id = 101;
strcpy(record.name, "Alice");
record.percentage = 92.5;
// Passing individual members to function
displayStudent(record.id, record.name, record.percentage);
return 0;
}
Student ID: 101 Student Name: Alice Percentage: 92.50%
Key Points
- Value Passing: Individual members are passed by value, so modifications inside the function don't affect the original structure
- Type Matching: Function parameters must match the data types of structure members being passed
- Memory Efficient: Only the required members are passed, not the entire structure
- Multiple Arguments: Each member becomes a separate function parameter
Conclusion
Passing individual structure members as function arguments is useful when you only need to work with specific members. This approach provides clear parameter isolation and prevents unintended modifications to the original structure data.
