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

(Romina) #1
change(char name[15]) // Recieves the value of i
{
// Change the string stored at the address pointed to by name
strcpy(name, "XXXXXXXXXXXXXX");
return; // Returns to main
}

This program produces the following output:


Click here to view code image


Back in main(), the name is now XXXXXXXXXXXXXX.

If you want to override the passing of non-arrays by value, you can force C to pass regular non-array
variables by address. However, doing so looks really crazy! Here is a program, similar to the first
one you saw in this chapter, that produces a different output:


Click here to view code image


// Example program #3 from Chapter 31 of Absolute Beginner's Guide
// to C, 3rd Edition
// File Chapter31ex3.c
/* The program demonstrates passing a variable to a function by
address. */
#include <stdio.h>
main()
{
int i;
printf("Please enter an integer... ");
scanf(" %d", &i);
// Now call the half function, passing the address of i
half(&i);
// Shows that the function did alter i's value
printf("In main(), i is now %d.\n", i);
return(0); // Ends the program
}
/******************************************************************/
/* Sometimes putting dividers like the one above is a nice break
between your different functions. */
half (int *i) // Receives the address of i
{
*i = *i / 2;
printf("Your value halved is %d.\n", *i);
return; // Returns to main
}

Here is the output from the program:

Free download pdf