next up previous contents

[ENGN3213 Home]

Pointers

We saw in CLAB6 how parameters can be passed by value or reference. C uses pointers to pass parameters by reference. We look at several examples.

Download the C program clab73c.c:

/*     clab73c.c    */

#define number 12

int adder(int x, int *py)
{
     return x + *py;
}

int main()
{
  int a, b, c;
  a = 1; b = number;
  c = adder(a, &b);
}

Exercise.

1.
What does this program do? Which variables are pointers?

2.
Compile, assemble and link this program.

3.
Load the program clab73c.s19 into the BSVC simulator. Run the code and check for correct operation.

4.
Examine the assembly code produced by the compiler in the file clab73c.s (or in the listing file clab73c.lst). How are the variables stored in main and adder?

5.
How are parameters passed to the subroutine? What are they? Are they passed by value or reference?

Clements, page 178, gives an example of a subroutine which attemps to swap numbers in variables. Download the C program swap1c.c:

/*    swap1c.c  Clements, page 178 */

void  swap(int a, int b)
{
  int temp;
  temp = a;
  a = b;
  b = temp;
}

int main()
{
  int x = 2, y  = 3;
  swap(x, y);
  return 0;
}

Exercise.

1.
What does this program try to do? Are there any pointers?

2.
Compile, assemble and link this program.

3.
Load the program swap1c.s19 into the BSVC simulator. Run the code and check for correct operation.

4.
Examine the assembly code produced by the compiler in the file swap1c.s (or in the listing file swap1c.lst). How are the variables stored in main and swap?

5.
How are parameters passed to the subroutine? What are they? Are they passed by value or reference?

6.
Why doesn't this program work?

Download the C program swap2c.c:

/*    swap2c.c  Clements, page 181 */

void  swap(int *a, int *b)
{
  int temp;
  temp = *a;
  *a = *b;
  *b = temp;
}

int main()
{
  int x = 2, y  = 3;
  swap(&x, &y);
  return 0;
}

This program does what we want correctly.

Exercise.

1.
What does this program do? Are there any pointers?

2.
Compile, assemble and link this program.

3.
Load the program swap2c.s19 into the BSVC simulator. Run the code and check for correct operation.

4.
Examine the assembly code produced by the compiler in the file swap2c.s (or in the listing file swap2c.lst). How are the variables stored in main and swap?

5.
How are parameters passed to the subroutine? What are they? Are they passed by value or reference?

6.
Why does this program work?


next up previous contents

[ENGN3213 Home]

ANU Engineering - ENGN3213