【问题标题】:C: inputs to a function left unaltered by the functionC:函数的输入保持不变
【发布时间】:2013-08-01 16:59:52
【问题描述】:

我在 C 语言中有一个函数,我想输出四个不同的值,因此我决定将四个不同的变量作为函数的参数,而不是在函数中使用 return,这些变量会将它们的值从函数中带回我的main 代码。我想如果我在main 中定义变量并将它们提供给我的另一个函数,它们将具有函数在退出函数后赋予它们的任何值。这不会发生。变量最终的值为 0 或接近 0(例如,大约 10^-310)。

我是否必须以不同的方式/具有不同的范围声明我的变量,以允许它们在退出函数后保留它们在函数中的值?或者有没有办法在一个函数中return多个值?

以下是相关代码的摘录:

void PeakShift_FWHM_Finder(double fwhml,double fwhmr,double peak, double max)
{
  ...//stuff happens to these variables
}

int main()
{
  double fwhml,fwhmr,peak,max;

  ...//other stuff to other variables

  PeakShift_FWHM_Finder(fwhml,fwhmr,peak,max)
  //These four variables have the right values inside the function
  //but once they leave the function they do not keep those values.

  ...//code continues...
  return 0;
}

【问题讨论】:

    标签: c function scope


    【解决方案1】:

    改用指针。

    void PeakShift_FWHM_Finder(double *fwhml,double *fwhmr,double *peak, double *max)
    {
      ...//stuff happens to these variables
        // REMEMBER TO DEAL WITH (*var_name) INSTEAD OF var_name!
    }
    
    int main()
    {
      double fwhml,fwhmr,peak,max;
    
      ...//other stuff to other variables
    
      PeakShift_FWHM_Finder(&fwhml,&fwhmr,&peak,&max)
      //These four variables have the right values inside the function
      //but once they leave the function they do not keep those values.
    
      ...//code continues...
      return 0;
    }
    

    【讨论】:

    • 我完全按照你上面说的做,但是从函数内部编译时出现以下错误:error: invalid operands to binary < (have ‘double *’ and ‘double’)error: incompatible types when assigning to type ‘double *’ from type ‘double’。我是否需要在每次使用变量时添加*?我猜这是有道理的,因为您需要像之前所说的那样直接指向函数中内存中的值。
    • 是的,您需要取消引用PeakShift 函数中的每个变量。因此我的评论是大写的。
    【解决方案2】:

    您正在寻找的是一种称为通过引用传递

    为此,您需要更改声明以获取指向变量的指针。例如

    void foo(int * x) {
        (*x)++;
    }
    

    然后,您可以简单地调用该函数,通过它们的地址将值传递给它。

    int main() {
        int i = 10;
        foo(&i);
        printf("%d", i);
    }
    

    它的作用是传递要修改的变量的地址位置,函数直接修改该地址处的变量。

    【讨论】:

    • foo 内,表达式应该是(*x)++。否则你正在做指针运算,这不是预期的。
    • 我猜这就是您在凌晨 4 点输入答案时发生的情况。谢谢!
    • @Shredderroy,原来的x++会指向内存中下一个int大小的字节块吗?
    • @Joshua 是的,会的。
    • 严格来说,这不是按引用传递(C 也不支持按引用传递)。您在这里所做的是按值传递,但您传递的是指向您感兴趣的对象的指针。您得到的效果几乎相同,但并不完全相同。
    猜你喜欢
    • 1970-01-01
    • 2010-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-19
    • 2017-04-03
    • 1970-01-01
    相关资源
    最近更新 更多