繁体   English   中英

从C中的函数返回多个值

[英]Returning multiple values from a function in C

int getPositionsH(int r, int ans, int size){
    int x=0;
    int y=0;
        if (ans==9){
            x =0;
        } else
            x=(rand()%size);

        y=(rand()%10);  
    return x;
    return y;
}

基本上这是c中的一个函数,它应该返回2个随机生成的位置x和y。 但是在调试时我注意到执行此操作后x和y仍为空。 不知道为什么因为我写了回报和一切。 有什么想法吗? 任何帮助表示赞赏。

函数只能在C中返回一个值。实际上,函数只返回x而语句return y; 没有效果 - 它是无法访问的代码。

如果要返回多个值,可以传递指针并返回其内容中的值,也可以创建结构并返回值。

typedef struct position {
   int x;
   int y;
}pos_type;

pos_type getPositionsH(int r, int ans, int size){
    pos_type p;
    int x=0;
    int y=0;
        if (ans==9){
            x =0;
        } else
            x=(rand()%size);

        y=(rand()%10);  

    p.x = x;
    p.y = y;
    reutrn p;
 }

并在来电者:

pos_type t = getPositionsH(...);

int x = t.x;
int y = t.y;
.....

你不能以这种方式返回两个值。

int getPositionsH(int r, int ans, int size)

被声明为int返回值将只返回一个int

 return x;
 return y;

返回x后,程序执行将从函数返回 ,因此返回y将无法访问。

使用xy的指针。 该函数不是返回值,而是设置值:

void getPositionsH(int r, int ans, int size, int *x, int *y) {
    *x = ans == 9 ? 0 : rand() % size;
    *y = rand() % 10;
}

被称为

int x,y;
getPositionsH(r, ans, size, &x, &y);
// use x and y as you wish...
int total = x + 7 * y;

getPositionsH被赋予两个指针(地址)到x和y。 使用*x =设置x的值(函数调用之前声明)。


注意

  *x = ans == 9 ? 0 : rand() % size; 

声明相当于

  if (ans == 9) *x = 0; else *x = rand() % size; 

返回x; 回归y;

你用过return x 这个函数会将值返回给调用函数现在它不会再返回并再次返回执行return y无论何时使用return语句,你都要记住实际返回语句的作用吗?

return语句终止函数的执行并将控制返回给调用函数

因此,您可以参考问答来解决您的问题。 其他答案也很不错。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM