Section 18.7 First Look at Modifying Arrays with Functions
Modifying the value of a variable inside a function isn’t quite as easy as it sounds. The techniques that we know of so far cannot accomplish this task (other than via using the return value of a function) as we can see via the
function1() example below. We’ll learn soon how to do this however!
But now look at
function2(). Given what we learned from function1() we’d expect the array variable in our main function not to get modified via the attempted change inside function2. See what happens though...
Compile and run the code below in your own C environment.
#include <stdio.h>
void function1(int a);
void function2(int b[]);
int main(void) {
int i = 3;
int array[] = {5, 6};
printf("Before function calls:\n");
printf("i = %d, array[0] = %d, array[1] = %d\n", i, array[0], array[1]);
printf("After function calls:\n");
printf("i = %d, array[0] = %d, array[1] = %d\n", i, array[0], array[1]);
return 0;
}
void function1(int a) {
printf("Inside function1: \n");
printf("a = %d.\n", a);
a = -7;
printf("Inside function1, after change: \n");
printf("a = %d.\n", a);
}
void function2(int b[]) {
printf("Inside function2: \n");
printf("b[0] = %d, b[1] = %d.\n", b[0], b[1]);
b[0] = -12;
printf("Inside function2, after change: \n");
printf("b[0] = %d, b[1] = %d.\n", b[0], b[1]);
}

