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:
- return an array of structures (pointer to the first element)
- or return an array of struct pointers?
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);