Back to: C Tutorials For Beginners and Professionals
How to Pass Structure as a Parameter to a Function in C Language
In this article, we will discuss How to Pass Structure as a Parameter to a Function in C Language with Examples. Please read our previous article discussing How to pass an Array as a Parameter to a function. If we send a structure as a parameter to a function, it may be call-by-value or call-by-address. At the end of this article, you will understand the following pointers:
- Passing Structure as a Parameter to a Function using Call by Value
- Passing Structure as a Parameter to a Function using Call by Address
- Returning a Structure from a Function
- When to Pass Structure as a Parameter to a Function in C?
- Structure as a Parameter in C Real-Time Examples
Passing Structure as a Parameter to a Function using Call by Value in C Language:
Let us understand how to pass a structure as a parameter to a function using the call-by-value mechanism in C Language. To better understand this, let us first create a structure as shown below. As you can see in the below image, we have a structure called a Rectangle having two properties: length and breadth.
Now, we need to create a function called CalculateArea, which should calculate the area of a rectangle. Now, here, shall we pass length separate and breadth separate? There is no need. We can send the structure itself as a parameter, which is the benefit of using a structure. We can send the structure itself, which carries both length and breadth. For a better understanding, please have a look at the below image.
Now, in the main function, we need to create a variable of type structure, and then we need to pass that structure as a parameter to the CalculateArea function, as shown in the image below.
The complete code is given below.
#include <stdio.h> struct Rectangle { int length; int breadth; }; int CalculateArea (struct Rectangle rect2) { return rect2.length * rect2.breadth; } int main () { struct Rectangle rect1 = { 10, 5 }; printf ("%d", CalculateArea (rect1)); }
Code Explanation and Memory Representation:
Within the main function, first, we created a variable rect1 of type structure rectangle, and it initialized it with values 10 and 5. Here, 10 will be assigned to length, and 20 will be assigned to breadth. Then, we call the function CalculateArea by giving the structure rect1 as a parameter. In the CalculateArea function, we defined one parameter of type structure Rectangle, and this parameter is called by value as we have not specified either * or &.
As we already discussed in our previous article, in pass-by-value, new memory allocation will happen, and the values are copied. So, here, a new rectangle object rect2 will be created, and the values 10 and 5 are copied to the length and breadth properties. Then, the CalculateArea function calculates the area and returns that value, which will be printed in the console window. For a better understanding, please have a look at the below diagram.
Now, inside the CalculateArea function, if we change the rect2 object, it will not affect the rect1 object inside the main method. This is because, in the call-by-value, we are just passing a copy of the value. For a better understanding, please have a look at the below code.
#include <stdio.h> struct Rectangle { int length; int breadth; }; int CalculateArea (struct Rectangle rect2) { rect2.length = 20; rect2.breadth = 15; return rect2.length * rect2.breadth; } int main () { struct Rectangle rect1 = { 10, 5 }; printf ("%d", CalculateArea (rect1)); }
The following image is the memory representation of the above example.
Passing Structure as a Parameter to a Function using Call by Address in C Language
Let us understand How to Pass Structure as a Parameter to a Function using Call by Address in C Language with an example. Now, our requirement is to change the length of a rectangle. We can change the length within the main function, but we don’t want to do any business operations within the main method. The main function role is to assign the task or manage the task. So, when you want to modify the actual parameter, it should be called by address or call-by-reference. For a better understanding, please have a look at the following code.
#include <stdio.h> struct Rectangle { int length; int breadth; }; void changelength(struct Rectangle *p) { p->length = 20; } int main () { struct Rectangle r = { 10, 5 }; changelength(&r); }
As you can see above, within the main function, first, we create an object of struct Rectangle and assign it 10 and 5. Then we call the changelength function by passing the & of the rectangle object, i.e., &r. We also know the point is only responsible for holding the address. So, in the changelength function, we create one parameter of type structure pointer, i.e., struct Rectangle *p. That means the pointer p now points to the rectangle r object. for accessing the structure member indirectly using a pointer, we have to use the -> operator, i.e., p -> length = 20; this length would be modified to 20 in the structure object. Following is the memory representation of the above example.
Pass Structure as a Parameter to a Function in C
Passing a structure to a function in C can be done in two main ways: by value or by reference. Each method has its own use cases and implications.
Passing by Value
When you pass a structure by value, the entire structure is copied into the function’s parameters. This means any changes to the structure inside the function do not affect the original structure.
#include <stdio.h> typedef struct { int x; int y; } Point; void modifyPoint(Point p) { p.x = 100; // This will modify the copy, not the original structure p.y = 200; printf("Inside Function: x = %d, y = %d\n", p.x, p.y); } int main() { Point pt = {10, 20}; modifyPoint(pt); printf("In Main: x = %d, y = %d\n", pt.x, pt.y); // Original structure remains unchanged return 0; }
Passing by Reference (Using Pointer)
Passing a structure by reference involves passing a pointer to the structure. This method is more memory-efficient, especially for large structures, and allows the function to modify the original structure.
#include <stdio.h> typedef struct { int x; int y; } Point; void modifyPoint(Point *p) { p->x = 100; // This modifies the original structure p->y = 200; printf("Inside Function: x = %d, y = %d\n", p->x, p->y); } int main() { Point pt = {10, 20}; modifyPoint(&pt); printf("In Main: x = %d, y = %d\n", pt.x, pt.y); // Original structure is modified return 0; }
Key Points:
- Performance: Passing by value involves copying the entire structure, which can be inefficient for large structures. Passing by reference is more efficient as it only passes the address.
- Memory Usage: Passing by reference is more memory efficient.
- Function Side-Effects: Passing by reference allows the function to modify the original structure. This can be both an advantage and a disadvantage, depending on whether such modification is intended.
- Safety: Passing by value is safer in terms of preventing unintended side effects, as the function works on a copy of the structure.
Returning a Structure from a Function
You can also return a structure from a function. This can be useful when you need to create or modify a structure and then return the new or modified version.
#include <stdio.h> typedef struct { int x; int y; } Point; // Function to create a new Point Point createPoint(int x, int y) { Point p; p.x = x; p.y = y; return p; // Returning a structure } int main() { Point pt = createPoint(30, 40); printf("New Point: (%d, %d)\n", pt.x, pt.y); return 0; }
When to Pass Structure as a Parameter to a Function in C?
Deciding when to pass a structure as a parameter to a function in C depends on the specific requirements of your program and the operations you intend to perform on the structure. Here are some guidelines to help you make this decision:
Pass by Value
You should pass a structure by value when:
- No Modification Needed: If the function does not need to modify the original structure, passing by value can be a good choice. This ensures that the original data remains unchanged.
- Small Structures: For small structures, the overhead of copying the data might be negligible, making passing by value a simple and straightforward option.
- Safety: Passing by value is safer regarding accidental data modification, as the function works with a copy rather than the original data.
Pass by Reference (Using Pointers)
Passing a structure by reference is usually preferred when:
- Modification Required: If the function needs to modify the original structure, you must pass it by reference. This allows the function to modify the original data directly.
- Large Structures: Passing by reference is more efficient for large structures as it avoids the overhead of copying the entire structure. This can significantly improve performance for large data.
- Memory Efficiency: Passing by reference is more memory-efficient, as it only involves passing a pointer rather than the entire structure.
- Returning Multiple Values: If you need the function to return multiple values via the structure, passing by reference is the way to go.
Return a Structure
You might return a structure from a function when:
- Creating or Initializing Structures: If the purpose of the function is to create or initialize a structure, returning the structure is a natural choice.
- Functional Approach: In a functional programming style, where functions do not have side effects, returning a new structure can be preferred instead of modifying an existing one.
Considerations
- Performance vs. Safety: There is often a trade-off between performance and safety. Passing by reference is faster but can lead to side effects if the function unintentionally modifies the data. Passing by value is safer but can be slower for large structures.
- Const Correctness: When passing by reference and you do not want the function to modify the structure, use const pointer parameters to enforce read-only access to the structure.
- Consistency: Stick to a consistent strategy throughout your codebase to make the code easier to understand and maintain.
Structure as a Parameter in C Real-Time Examples
Using structures as function parameters in C is common for organizing and managing complex data in real-time applications. Here are a few practical examples where structures are used as parameters:
Geometric Calculations
Suppose you have a structure representing a point in 2D space and want to perform various calculations like distance, midpoint, etc.
typedef struct { double x; double y; } Point; double calculateDistance(Point a, Point b) { return sqrt(pow(a.x - b.x, 2) + pow(a.y - b.y, 2)); }
Sensor Data Processing in Embedded Systems
In embedded systems, you might have a structure representing data from a sensor, and you pass this structure to functions for processing.
typedef struct { int temperature; int pressure; int humidity; } SensorData; void processSensorData(SensorData data) { // Process the data... }
Networking Applications
In networking, structures are used to represent packets or messages, which are then passed to functions for processing, serialization, or deserialization.
typedef struct { char header[10]; char body[50]; } NetworkPacket; void serializePacket(NetworkPacket packet, char *buffer) { // Convert NetworkPacket to a byte stream }
Graphics and UI Programming
In graphical applications, structures representing graphical objects like windows, buttons, or other UI elements are commonly passed to functions.
typedef struct { int width; int height; char title[100]; } Window; void resizeWindow(Window *win, int newWidth, int newHeight) { win->width = newWidth; win->height = newHeight; }
Database Operations
Structures are often used to represent records in a database. These structures can be passed to functions that handle database operations.
typedef struct { int id; char name[100]; float salary; } Employee; void addEmployeeRecord(Employee emp) { // Add the employee record to the database }
In the next article, I will discuss Command Line Arguments in C Language with Examples. In this article, I explain How to pass Structure as a Parameter to a function in C Language. I hope you enjoy this article, “How to Pass Structure as a Parameter to a Function in the C Language.”