Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

c function returns two pointers with different types

My function should return 2 pointers to different structures.

struct a {
   ...
};

struct b{
   ...
};

The 2 options that I see for my functioin are:

1

void myFunction(struct a *s_a, struct_b *s_b){
    s_a = &a;
    s_b = &b;
    do something with s_a and s_b;

};

2

struct c{
  *a...;
  *b...;
}
 
struct c myFunction(){
   ...
   return c
}

Are these options correct? Which is better? why?

Thank you!

P.S. 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.7k users

...