Use Structures with Functions
Functions and structures cooperate in a number of ways:
- Passing Individual Structure Members: A structure’s individual members can be sent to a function. Like any other ordinary variable, these elements are usually provided by value.
- A sample snippet that passes particular members.
- Passing Entire Structures by Value: An complete structure variable can be passed to a function as an argument. A local duplicate of the full structure is created for usage within the called function when a structure is supplied in this manner.
- The initial structure variable in the calling function is unaffected by modifications made to the structure’s members inside the function. Only the copy is impacted.
- Because the entire structure must be copied, passing huge structures by value can be somewhat wasteful.
- An example of passing a structure by value in a snippet .
- Passing Pointers to Structures (Pass-by-Reference): The address of the structure object is passed to the function in order to pass a structure by reference.
- This is comparable to sending an array which are automatically passed by reference to a function. Structure object arrays are passed by reference automatically.
- A pointer to the original structure is passed to the called function.
- The function can work directly on the original structure and gain indirect access by using a pointer.
- Any changes made to any members of the structure inside the function will be detected outside of it. This method allows a function to change caller variables or “return” multiple values.
- Since the full structure is not copied, this approach is typically more effective than pass-by-value for big structures.
- The arrow operator (->) with the structure pointer is used to access members of the structure within the function.
Returning Structures from Functions
An full structure can also be returned by a function. A copy of the structure is made and sent back to the calling function whenever a function returns one.
It is possible to return a structure. A function header for a function update that returns a structure of the same type as employee_data after accepting a structure by value is displayed.
An example showing how to return a structure (structure return types; nevertheless, there isn’t a complete runnable example):
#include <stdio.h>
// Define a structure for a point in 2D space
struct point {
int x;
int y;
};
// Function that takes two integers and returns a struct point
// Similar to concept of makepoint
struct point make_point(int x_val, int y_val) {
struct point p;
p.x = x_val;
p.y = y_val;
return p; // Return the created structure
}
int main(void) {
// Call the function to create a point structure
struct point origin = make_point(0, 0);
// Access and print the members of the returned structure
printf("Point coordinates: (%d, %d)\n", origin.x, origin.y);
return 0;
}
Output:
Point coordinates: (0, 0)