How to Return Structure from Function in C: Simple Guide
In C, you can return a structure from a function by specifying the structure type as the function's return type and returning a structure variable. Use
struct in the function signature and return a complete structure instance from the function body.Syntax
To return a structure from a function, declare the function's return type as the structure type. Inside the function, create and fill a structure variable, then use return to send it back.
- struct TypeName: The structure type you want to return.
- functionName(): The function that returns the structure.
- return variable;: Returns the structure variable.
c
struct TypeName {
int field1;
float field2;
};
struct TypeName functionName() {
struct TypeName var;
var.field1 = 10;
var.field2 = 3.14f;
return var;
}Example
This example shows a function that creates a Point structure with x and y coordinates and returns it. The main function prints the returned values.
c
#include <stdio.h>
struct Point {
int x;
int y;
};
struct Point createPoint(int x, int y) {
struct Point p;
p.x = x;
p.y = y;
return p;
}
int main() {
struct Point myPoint = createPoint(5, 10);
printf("Point coordinates: x = %d, y = %d\n", myPoint.x, myPoint.y);
return 0;
}Output
Point coordinates: x = 5, y = 10
Common Pitfalls
One common mistake is returning a pointer to a local structure variable, which becomes invalid after the function ends. Always return the structure itself, not a pointer to a local variable.
Also, avoid returning structures that are too large for performance reasons; in such cases, consider passing a pointer to a structure as a function argument instead.
c
/* Wrong way: returning pointer to local variable */ struct Point* wrongFunction() { struct Point p = {1, 2}; return &p; // p is local and will be destroyed } /* Right way: return structure by value */ struct Point rightFunction() { struct Point p = {1, 2}; return p; // safe to return }
Quick Reference
- Declare function return type as the structure type.
- Return a fully initialized structure variable.
- Do not return pointers to local variables.
- Use
typedefto simplify structure type names if desired.
Key Takeaways
Return structures by value using the structure type as the function return type.
Never return pointers to local structure variables from functions.
Initialize the structure fully before returning it.
Use typedef to make structure types easier to use.
For large structures, consider passing pointers instead of returning by value.