I want to write a function prototype for a function, whose argument is a pointer to a struct.
int mult(struct Numbers *n)
However, the struct Numbers, which is defined as
struct Numbers {
int a;
int b;
int c;
};
is not defined yet. How should I write a suitable prototype for mult?
We can pass the C structures to functions in 3 ways: Passing each item of the structure as a function argument. It is similar to passing normal values as arguments. Although it is easy to implement, we don't use this approach because if the size of a structure is a bit larger, then our life becomes miserable.
Structures can be passed as function arguments like all other data types. We can pass individual members of a structure, an entire structure, or, a pointer to structure to a function. Like all other data types, a structure or a structure member or a pointer to a structure can be returned by a function.
You can also pass structs by reference (in a similar way like you pass variables of built-in type by reference). We suggest you to read pass by reference tutorial before you proceed. During pass by reference, the memory addresses of struct variables are passed to the function.
Passing of structure to the function can be done in two ways: By passing all the elements to the function individually. By passing the entire structure to the function.
Just declare struct Numbers
as an incomplete type before your function declaration:
struct Numbers;
int mult(struct Numbers *n);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With