是否可以从函数返回多个值并将它们分配给多个变量?将多个值返回给多个变量
可以说我有其产生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一个的值先分配到变量,二至第二和三个第三。是这样的可能使用C吗?
是否可以从函数返回多个值并将它们分配给多个变量?将多个值返回给多个变量
可以说我有其产生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一个的值先分配到变量,二至第二和三个第三。是这样的可能使用C吗?
你可以通过变量的地址,要分配一个值:
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 };
}
或通过函数参数填充它[R ,类似于第一种方法:
void generator(struct data* d) {
int one, two, three;
/* Fill one, two, and three here. */
d->one = one;
d->two = two;
d->three = three;
}
1作为意见建议@CraigEstey这个答案
这两个都是很好的例子。如何添加第三个:void generator(struct data *);'?它通常更清晰,特别是如果调用者需要从部分init例程构建结构,如:init1(stp); INIT2(STP); ...' –
@CraigEstey新增,谢谢。 – Downvoter
你可以参考 –
没有传递参数,它不可能从一个函数返回多个值,但还有其他方法可以做到这一点。 – haccks
在发布之前,您是否尝试找到答案?我在Google中输入了“在c中返回多个值”,并在10秒内找到了问题的答案。 –