BIT 142 – SPRING 2001 - Cascadia College



Pointers And Arrays; Pointers and Objects

Note: Please keep the programs that you create today, in case you have a dispute about your grades for the ICEs at the end of the quarter

Arrays

Part 1: Print the first element of an array (Optional)

Write a function named Print that has a single parameter: a pointer to a character. Your function should print out the value that this parameter points to (don't print out the value of the pointer itself!) In main, create an array of, say, 4 characters, and initialize the array to hold some data. Use the Print function to print out the value of the first element of an array. You should be able to print out that element using a pointer, both by dereferencing it, and by using standard array notation. Within main, you should be able to print out the first element of the array using the array directly, again by both dereferencing it, and by using the standard array syntax.

Part 2: Print everything in an array

You should create a function named Print which has two parameters – the first is a pointer (to the first element in the array), the second is an integer representing the number of spaces in the array. Print should print all the elements of the array.

The first issue that you'll need to tackle is how your Print function will know the length of the array. Even though Print uses a pointer to access the array elements, the memory itself is still an array. Thus, you'll need to use the second parameter to know when to stop.

How will you print all the elements of the array? At this point, you basically have to use pointer arithmetic 1. There are two ways that you can go about doing this

1. Repeatedly adding an ever-increasing number to a pointer (whose value doesn't change)

2. Repeatedly moving the pointer's value up by one

(This will move the pointer “forwards” one array element.)

You want to learn both methods.

Method 1:

If your original parameter is named ptrChar, you could write:

cout ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download