Tra*_*kel 116
我不知道你string是什么,但我会假设它管理自己的记忆.
你有两个解决方案:
1:返回struct包含您需要的所有类型的a .
struct Tuple {
int a;
string b;
};
struct Tuple getPair() {
Tuple r = { 1, getString() };
return r;
}
void foo() {
struct Tuple t = getPair();
}
Run Code Online (Sandbox Code Playgroud)
2:使用指针传递值.
void getPair(int* a, string* b) {
// Check that these are not pointing to NULL
assert(a);
assert(b);
*a = 1;
*b = getString();
}
void foo() {
int a, b;
getPair(&a, &b);
}
Run Code Online (Sandbox Code Playgroud)
您选择使用哪一个在很大程度上取决于您喜欢的任何语义的个人偏好.
cod*_*ict 10
Option 1:使用int和string声明一个struct并返回一个struct变量.
struct foo {
int bar1;
char bar2[MAX];
};
struct foo fun() {
struct foo fooObj;
...
return fooObj;
}
Run Code Online (Sandbox Code Playgroud)
Option 2:您可以通过指针传递两个中的一个,并通过指针更改实际参数,并像往常一样返回另一个:
int fun(char **param) {
int bar;
...
strcpy(*param,"....");
return bar;
}
Run Code Online (Sandbox Code Playgroud)
要么
char* fun(int *param) {
char *str = /* malloc suitably.*/
...
strcpy(str,"....");
*param = /* some value */
return str;
}
Run Code Online (Sandbox Code Playgroud)
Option 3:类似于选项2.您可以通过指针传递两者并从函数中返回任何内容:
void fun(char **param1,int *param2) {
strcpy(*param1,"....");
*param2 = /* some calculated value */
}
Run Code Online (Sandbox Code Playgroud)
创建一个struct并在其中设置两个值并返回struct变量.
struct result {
int a;
char *string;
}
Run Code Online (Sandbox Code Playgroud)
您必须为char *程序中的空间分配空间.
两种不同的方法:
我认为#1对于正在发生的事情更为明显,尽管如果你有太多的回报值,它会变得乏味.在这种情况下,选项#2工作得相当好,尽管为此目的制作专门的结构有一些精神上的开销.
由于您的一个结果类型是一个字符串(并且您使用的是C而不是C++),我建议将指针作为输出参数传递.使用:
void foo(int *a, char *s, int size);
Run Code Online (Sandbox Code Playgroud)
并称之为:
int a;
char *s = (char *)malloc(100); /* I never know how much to allocate :) */
foo(&a, s, 100);
Run Code Online (Sandbox Code Playgroud)
通常,更喜欢在调用函数中进行分配,而不是在函数本身内部进行分配,这样您就可以对不同的分配策略尽可能地开放.
| 归档时间: |
|
| 查看次数: |
257217 次 |
| 最近记录: |