1

I have a function in C that I want to output four different values, so rather than using return in my function I decided have four different variables as arguments to the function that would carry their values out of the function back into my main code. I figured if I defined the variables in main and fed them to my other function, they would have whatever value the function gave them after exiting the function. This does not happen though. The variables end up having a value of 0 or close to 0 (like, around 10^-310).

Do I have to declare my variables in a different way/with a different scope to allow them to keep the values they had in a function after exiting the function? Or is there a way to return multiple values in a function?

Here's an excerpt of the relative code:

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;
}
4

2 回答 2

4

改用指针。

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;
}
于 2013-07-31T23:31:57.100 回答
2

您正在寻找的是称为通过引用传递的东西

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

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

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

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

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

于 2013-07-31T23:36:46.140 回答