Bifalgorithm post · Computer science one · Function Pointers

How do pointers pass values by reference in C?

How do pointers pass values by reference in C? (Computer science one · Function Pointers) — "int *ptrC = &c;\n\nsum(x, y, ptrC);\n\n//at this point c contains…

Ideas in this flowchart

  • Passing variables by reference with pointers in C
  • The address of c is stored in ptrC: int *ptrC = &c;
  • The pointer ptrC is passed to sum(x, y, ptrC).
  • After the call, c contains the value 30.
  • The addresses of x and y are passed to swap(&x, &y).
  • After the call, x contains 20 and y contains 10.
  • scanf() uses the same ampersand syntax to receive variables by reference.
  • Passing variables by value would prevent scanf() from manipulating their values.
  • Functions can also be specified to return pointers.
  • Pointer-returning functions are discussed in detail in Chapter 20.
Feed/

How do pointers pass values by reference in C?

No cover

Channel

Computer science one

1 page

"int *ptrC = &c;\n\nsum(x, y, ptrC);\n\n//at this point c contains the value 30\n\nswap(&x, &y);\n\n//at this point, the values in x and y have been swapped\n\n// x contains 20 and y contains 10\n\nThis should look familiar. We saw this same syntax when we used scanf() to read input from the standard input. We needed to place an ampersand in front of each variable in order to pass the variable by reference so that scanf() could place the results into the respective memory locations. If the variables had been passed by value, then scanf() would not have been able to manipulate their values. You can also specify functions to return pointers which we discuss in detail in Chapter 20."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.