CS 220 Parallel Computing

arg_example2.c

DownloadView Raw

/**
 * arg_example2.c
 *
 * Simulates passing values by reference using pointers.
 *
 * 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_p, int* y_p, int* z_p);

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

   printf("Enter three ints\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_p, int* y_p, int* z_p) {
    printf("In pass_by_reference, x = %d, y = %d, z = %d\n", *x_p, *y_p, *z_p);
   /* Let's manipulate these variables here: */
    *x_p = 2 + *x_p;
    *y_p = *y_p - 3;
    *z_p = 7 + *z_p;
   /* Print out the changes: */
    printf("In pass_by_reference, x = %d, y = %d, z = %d\n",
            *x_p, *y_p, *z_p);
}