Lesson 8

ArtyArty
2 min read

Simulate pass by reference

  • When we pass a variable, we pass the variable to the function. When we pass the address, we simulate pass-by-reference.

    • void pass_by_value(int a); copies the value into the function

    • void pass_by_reference(int *a); passes the address into the function affecting the original value if the function changes it.

  • If we don’t plan on change the reference, we can simply use the const keyword (void pass_by_reference(const int *a);).

  • A common pattern is to use pointers to bring back a value from the function:

      /*
      Return larger value, extract the smallest value via pointer
      */
      int max_min(int a, int b, int *smallest) {
          if (a > b) {
              *smallest = b;
              return a;
          }
    
          *smallest = a;
          return b;
      }
    

Array of pointers

  • int arr[3] is an array of integers.

      int arr[3] = {1, 2, 3};
      printf("%d\n", arr[0]); // prints 1
    
  • int *arr[3]; is an array of integer pointers.

      int arr[3] = {1, 2, 3};
      int *arrp[3] = {arr, arr + 1, arr + 2};
      printf("%d\n", *arrp[0]); // prints 1
    
  • int (*arr)[3]; is a pointer that points to an array of 3 integers.

      int arr[3] = {1, 2, 3};
      int (*arrp)[3] = &arr;
      printf("%d\n", (*arrp)[0]); // prints 1
    

Pointer to pointer

  • We can pointer to another pointer

      int a = 3;
      int *b = &a;
      int **c = &b;
      int ***d = &c;
    
0
Subscribe to my newsletter

Read articles from Arty directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Arty
Arty