If you need to return a struct
from a function, you would normally return a pointer to the struct
instead.
If you then want to return an array of structs, is it recommended to:
I have drawn a diagram for the two options below:
1:
2:
Given the following struct definition
struct values {
int a;
int b;
};
here is some sample code for accessing the fields of the structs from the two options:
Option #1:
struct values *vals = get_values1();
printf("%d, %d\n", values[0].a, values[1].b);
Option #2:
struct values **vals = get_values2();
printf("%d, %d\n", values[0]->a, values[1]->b);
It is not possible to return an array, unless the array itself is a member of a structure which is being returned.
Use Standard Notation to Return struct From Function Now, functions in C can return the struct similar to the built-in data types. In the following example code, we implemented a clearMyStruct function that takes a pointer to the MyStruct object and returns the same object by value.
It is not possible to create an array of pointer to structures.
The only issue I see to not use version 1, is that it might be easier to identify the number of structures (returned) in the second version, as a NULL
pointer can be used as a stopper element, whereas in the first version it might not be possible to define a stopper element.
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