gpt4 book ai didi

c - 将多个值返回给多个变量

转载 作者:行者123 更新时间:2023-11-30 20:05:05 26 4
gpt4 key购买 nike

是否可以从函数返回多个值并将它们分配给多个变量?

假设我有生成 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 one 的值分配给变量第一个,将两个值分配给第二个变量,将三个值分配给第三个变量。使用 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 };
}

或者通过函数参数填写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;
}
<小时/>

1 由 @CraigEstey 在此答案的评论中提议

关于c - 将多个值返回给多个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33573738/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com