-2

I'm new to programming in C and I was looking at some code. 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? If that's what it does, how would you change it if you were to implement adjust?

Christophe
  • 68,716
  • 7
  • 72
  • 138
yosoup1989
  • 11
  • 2
  • 1
    this is a good place to start: https://www.tutorialspoint.com/cprogramming/c_pointers.htm – kennyvh Jan 16 '20 at 23:06
  • 5
    Read [pointers in C](https://www.tutorialspoint.com/cprogramming/c_pointers.htm) – CoderCharmander Jan 16 '20 at 23:07
  • Does this answer your question? [What is the difference between the \* and the & operators in c programming?](https://stackoverflow.com/questions/2702156/what-is-the-difference-between-the-and-the-operators-in-c-programming) – ShadowRanger Jan 16 '20 at 23:19
  • https://stackoverflow.com/q/4844914/315052 – jxh Jan 16 '20 at 23:26
  • Does this answer your question? [Function call in C using & in front of argument](https://stackoverflow.com/questions/35138680/function-call-in-c-using-in-front-of-argument) – phuclv Jan 17 '20 at 01:44
  • time to [read a good book](https://stackoverflow.com/q/562303/995714). They should explain everything faster and in more detail – phuclv Jan 17 '20 at 01:46

2 Answers2

0

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.

I recommend you to read:

Reference and dereference

pointers

Sinking
  • 95
  • 8
  • 2
    I would note that C is all *pass-by-value*, but that value may be an address to be passed into a pointer, as opposed to a language such as C++ which actually has a specific concept of *pass-by-reference* – Christian Gibbons Jan 17 '20 at 20:18
0

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:

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.

Christophe
  • 68,716
  • 7
  • 72
  • 138