首页 > 解决方案 > c函数返回两个不同类型的指针

问题描述

我的函数应该返回 2 个指向不同结构的指针。

struct a {
   ...
};

struct b{
   ...
};

我为我的功能看到的 2 个选项是:

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
}

这些选项是否正确?哪个更好?为什么?

谢谢!

PS我找不到这个问题的答案。我确信答案被伪装在另一个问题中,但我无法发现它。

免责声明:我实际上使用的是 typedef 而不是 struct。这就是为什么我提到两种不同的类型。

标签: cfunctionpointersstruct

解决方案


您的第一个选项不会根据需要返回指针。

说你有

typedef struct { ... } StructA;
typedef struct { ... } StructB;

以下是常用的:

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);
   ...
}

或者

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);
   ...
}

但是,是的,您可以使用结构作为返回值。

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;
   ...
}

它有点复杂,但不是非常复杂。


推荐阅读