c - 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。这就是为什么我提到两种不同的类型。
解决方案
您的第一个选项不会根据需要返回指针。
说你有
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;
...
}
它有点复杂,但不是非常复杂。
推荐阅读
- opengl-es - 关于opengl中帧缓冲区纹理的内存管理
- angular - 类中的打字稿联合
- python - mysql.connector.errors.ProgrammingError:1054(42S22):'where 子句'中的未知列'PY_VAR0'
- javascript - 如何将 javascript 函数舍入为 1.00 而不是 0.100?
- python - 卡在 Python Web 抓取中抓取 Novel 标题及其链接
- javascript - 在 reducer (redux) 中使用拼接
- python - 使用scrapy从表格行(tr)中提取td文本的问题
- django - Django中的错误上传路径
- blazor - 在 Blazor 中绑定完成后如何运行其他操作?
- c++ - mongo-cxx-driver 十进制值问题