是否可以从函数返回多个值并将它们分配给多个变量?
假设我有代码生成3个数字
int first, second , third
int generator (a,b,c){
int one , two ,three
//code that generates numbers and assign them into one, two three
}
我希望将int的值分配给变量first,two to second和three to third。使用C可以这样吗?
答案 0 :(得分:3)
您可以将要分配值的变量的地址传递给:
int generator(int* first, int* second, int* third) {
int one, two, three;
/* Initialize local variables here. */
*first = one;
*second = two;
*third = three;
return something;
}
int main(void) {
int first, second, third;
generator(&first, &second, &third);
}
另一种方法是创建struct
并返回struct
:
struct data {
int one, two, three;
};
并将其退回:
struct data generator() {
int one, two, three;
/* Initialize local variables here. */
return (struct data) { one, two, three };
}
或通过函数参数 1 填写,类似于第一种方法:
void generator(struct data* d) {
int one, two, three;
/* Fill one, two, and three here. */
d->one = one;
d->two = two;
d->three = three;
}
@CraigEstey在对此答案的评论中提出1