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 address of structure as an argument to function in C language?
Passing the address of a structure as an argument to a function allows the function to access and modify the original structure through a pointer. This technique is memory-efficient and enables direct manipulation of structure members.
Syntax
return_type function_name(struct structure_name *pointer_variable);
Key Points
The address of the structure is passed as an argument to the function.
It is collected in a pointer to structure in function header.
Advantages
No wastage of memory as there is no need of creating a copy again
No need of returning the values back as the function can access indirectly the entire structure and work on it.
Example
Here's how to pass the address of a structure to a function −
#include <stdio.h>
struct date {
int day;
int mon;
int yr;
};
void display(struct date *dt) {
printf("day = %d<br>", dt->day);
printf("month = %d<br>", dt->mon);
printf("Year = %d<br>", dt->yr);
}
int main() {
struct date d = {02, 01, 2010};
display(&d);
return 0;
}
day = 2 month = 1 Year = 2010
How It Works
- The
&dpasses the address of structuredto the function. - The parameter
struct date *dtreceives this address as a pointer. - The arrow operator
->is used to access structure members through the pointer.
Conclusion
Passing structure addresses to functions is an efficient method that saves memory and allows direct manipulation of structure data. This approach is particularly useful for large structures where copying would be expensive.
