L-27 MCS 260 Mon 22 Oct 2001
Below are the programs we used in class to introduce pointers.
/* L-27 MCS 260 Mon 22 Oct 2001 : addressing and derefencing
C has a fine mechanism for dealing with variables: we can
declare a pointer to an int variable. With the addressing
operator we store in the pointer the address of some int.
Here is the picture :
int *p,i = 17; p i
p = &i; +------+ +------+
| &i -|---> | 17 |
+------+ +------+
The program below shows how to manipulate variables indirectly
with the dereferencing operator. */
#include<stdio.h>
int main(void)
{
int *p, i = 17;
p = &i;
printf("Some variable i has value %d = %d.\n", i, *p);
printf("The address of i is %x = %x.\n", &i, p);
*p = 3;
printf("Via dereferencing we changed i into %d = %d.\n", i, *p);
return 0;
}
In the program below we introduce call by reference :
/* L-27 MCS 260 Mon 22 Oct 2001 : call by reference
To illustrate call by reference, the program below uses
a function "add" to sum a sequence of user given integers. */
void add ( int *sum, int n );
/* adds n to the sum */
#include<stdio.h>
int main(void)
{
int i, s = 0;
printf("Give sequence of integers (terminate with zero) : ");
while (scanf("%d",&i) > 0)
{
if (i == 0) break;
add(&s,i);
}
printf("The sum : %d.\n", s);
return 0;
}
void add ( int *sum, int n )
/* we pass the sum via call by reference,
while n is passed via call by value */
{
*sum += n;
}
The function in the following example has as output two values:
one as return value of the function and the other as called by
reference.
/* L-27 MCS 260 Mon 22 Oct 2001 : call by reference
The function below illustrates interest compounding. */
float interest ( float *amount, float rate );
/* returns the yield on the given amount after one year with
the given interest rate; this yield is added to the amount */
#include<stdio.h>
int main(void)
{
float principal, rate, yield;
printf("Give dollar amount : ");
scanf("%f", &principal);
printf("Give interest rate as percentage : ");
scanf("%f", &rate);
yield = interest(&principal,rate/100);
printf("The yield : $%.2f.\n", yield);
printf("Amount after compounding : $%.2f.\n", principal);
return 0;
}
float interest ( float *amount, float rate )
{
float y = *amount * rate;
*amount += y;
return y;
}