简体   繁体   English

&符号在函数调用中是什么意思?

[英]What does ampersand mean in function call?

I'm new to programming in C and I was looking at some code.我是 C 编程的新手,我正在查看一些代码。 I was wondering what the following means:我想知道以下是什么意思:

adjust(&total, adjustmentFactor);

I know that total and adjustmentFactor are both doubles, but since that this function does assign output to a variable, I'm assuming that the function changes what total points to?我知道totaladjustmentFactor都是双精度值,但是由于这个函数确实将输出分配给了一个变量,我假设该函数改变了 total 指向的内容? If that's what it does, how would you change it if you were to implement adjust?如果这就是它的作用,如果您要实施调整,您将如何更改它?

You can pass an argument to a function in two ways:您可以通过两种方式将参数传递给函数:

  1. By value按价值

    int total;总计;

    adjust(total);调整(总计);

    In this case, will be created a local copy of passed value.在这种情况下,将创建传递值的本地副本。 If you change it in some way that would not affect the 'total' value from the parent function.如果您以某种不会影响父函数的“总”值的方式更改它。

  2. By reference引用

    int total;总计;

    adjust(&total);调整(总计);

In this case, the address of 'total' variable will be passed and now if you change total inside adjust() in any way, the changes will be carried out with the total variable from the parent function.在这种情况下,'total' 变量的地址将被传递,现在如果您以任何方式更改 adjust() 内部的 total,更改将使用来自父函数的 total 变量执行。

I recommend you to read:我建议你阅读:

Reference and dereference 引用和解引用

pointers 指针

Yes, you are right: the ampersand takes the address of an lvalue (a variable) and passes it as pointer.是的,您是对的:与号获取左值(变量)的地址并将其作为指针传递。

Your adjust() function would look like:您的adjust()函数如下所示:

void adjust(double *a, double f) {
   ... do a lot of stuff
   *a = *a * f/2+1.0;     // dummy formula that will change the content 
   ...   
}; 

So in the function you'd use *a every time you'd want to use the value pointed at by the first argument, and everytim you want to assign a new value to the original variable.因此,在函数中,每次您想使用第一个参数所指向的值时都会使用*a ,并且每次您想为原始变量分配一个新值时。

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

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