My function should return 2 pointers to different structures.
struct a {
...
};
struct b{
...
};
The 2 options that I see for my functioin are:
void myFunction(struct a *s_a, struct_b *s_b){
s_a = &a;
s_b = &b;
do something with s_a and s_b;
};
struct c{
*a...;
*b...;
}
struct c myFunction(){
...
return c
}
Are these options correct? Which is better? why?
Thank you!
PS I couldn't find answers to this question out there. I am sure the answer is camouflaged in a different question but I couldn't spot it.
Disclamer: I am actually using typedef and not struct. That's why I mention 2 different types.
The first of your options doesn't return pointers as desired.
Say you have
typedef struct { ... } StructA;
typedef struct { ... } StructB;
The following is commonly used:
void myFunction(StructA **aptr, StructA **bptr) {
StructA *a = malloc(sizeof(StructA));
StructB *b = malloc(sizeof(StructB));
... do stuff with a and b ...
*aptr = a;
*bptr = b;
}
void caller(void) {
StructA *a;
StructB *b;
myFunction(&a, &b);
...
}
or
void myFunction(StructA **aptr, StructA **bptr) {
*aptr = malloc(sizeof(StructA));
*bptr = malloc(sizeof(StructB));
... do stuff with *aptr and *bptr ...
}
void caller(void) {
StructA *a;
StructB *b;
myFunction(&a, &b);
...
}
But yes, you could use a struct as a return value.
typedef struct {
StructA *a;
StructB *b;
} StructAB;
StructAB myFunction(void) {
StructA *a = malloc(sizeof(StructA));
StructB *b = malloc(sizeof(StructB));
... do stuff with a and b ...
return (StructAB){ .a = a, .b = b };
}
void caller(void) {
StructAB ab = myFunction();
StructA *a = ab.a;
StructB *b = ab.b;
...
}
It's a bit more complicated, but not extremely so.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.