arg_example2.c

DownloadView Raw

/**
 * arg_example2.c
 *
 * Simulates passing values by reference using pointers. Note that we still are
 * passing by value, but the difference is we are passing *memory addresses* and
 * then dereferencing them to make changes from inside the function.
 *
 * Compile:  Using Linux and gcc
 *           gcc -g -Wall -o arg_example2 arg_example2.c
 * Run:      ./arg_example2
 */

#include <stdio.h>

void pass_by_reference(int *x, int *y, int *z);

int main(void) {
   int x, y, z;

   printf("Enter three ints (ex: 1 2 3)\n");
   scanf("%d%d%d", &x, &y, &z);

   printf("In main, x = %d, y = %d, z = %d\n", x, y, z);
   pass_by_reference(&x, &y, &z);

   /* Last print statement. Will the output change? */
   printf("In main, x = %d, y = %d, z = %d\n", x, y, z);

   return 0;
}

void pass_by_reference(int *x, int *y, int *z) {
    printf("In pass_by_reference, x = %d, y = %d, z = %d\n", *x, *y, *z);
   /* Let's manipulate these variables here: */
    *x = 2 + *x;
    *y = *y - 3;
    *z = 7 + *z;
   /* Print out the changes: */
    printf("In pass_by_reference, x = %d, y = %d, z = %d\n",
            *x, *y, *z);
}