C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1

Click here to view code image


Please enter an integer... 28
Your value halved is 14.
In main(), i is now 14.

It looks strange, but if you want to pass a non-array by address, precede it in the passing function with
an & (address-of) symbol and then put a * (dereferencing) symbol in front of the variable everywhere
it appears in the receiving function. If you think you’re now passing a pointer to a function, you’re
exactly right.


Note

Now scanf() is not so unfamiliar. Remember that you put an & before non-array
variables but not before array variables that you pass to scanf(). When you call
scanf(), you must pass it the address of variables so that scanf() can change the
variables. Because strings are arrays, when you get a string from the keyboard, you
don’t put an address-of operator before the array name.

Here is a program that passes an integer i by value, a floating-point x by address, and an integer
array by address (as all arrays should be passed):


Click here to view code image


// Example program #4 from Chapter 31 of Absolute Beginner's Guide
// to C, 3rd Edition
// File Chapter31ex4.c
/* The program demonstrates passing multiple variables to a
function. */
#include <stdio.h>
// The following statement will be explained in Chapter 32
changeSome(int i, float *newX, int iAry[5]);
main()
{
int i = 10;
int ctr;
float x = 20.5;
int iAry[] = {10, 20, 30, 40, 50};
puts("Here are main()'s variables before the function:");
printf("i is %d\n", i);
printf("x is %.1f\n", x);
for (ctr = 0; ctr < 5; ctr++)
{
printf("iAry[%d] is %d\n", ctr, iAry[ctr]);
}
Free download pdf