Computer Science 381
Programming Unix in C

Winter Immersion 2014, The College of Saint Rose

Lab 4: Introduction to Pointers and Arrays
Recommended Due Date: Tuesday, January 7, 2014

In this lab you will start to learn about pointers and the closely related topics (at least for C programmers) of arrays and strings. Even if you never write a C program after this course, understanding how C programs manage pointers will improve your programming in nearly any language.

Read About It

Read the first 4 sections of Chapter 5 in K&R. It's only 11 pages, but it's a pretty intense 11 pages.

Question 1: In your own words in a sentence or two, explain what happens when you execute a statement like p = &c; at the top of page 94. (1 point)

Practice Program: Write a C program called swapper.c that demonstrates that the swap function in the middle of p. 95 does not perform a swap of the values passed in (from the perspective of the caller), but the swap function at the top of p. 96 does. Include tests that attempt to swap regular int variables as well as array entries. (7 points)

Question 2: Explain briefly, again in your own words, why the first swap function cannot work as intended. (2 points)

A Pointer/Array Example

See Example:
/home/cs381/examples/isort

The above example includes two C functions that each perform an insertion sort on an array of int. You can switch between the two implementations of the sorting function to verify that both do work.

Question 3: Draw memory diagrams (like those on p. 96, but show all varibles in existence in both main and the sort function) to show the state of memory during the second iteration of the for loop right before the while loop starts in the isort example. Include diagrams for an execution using the isort function as shown in the example and when that call is replaced with a call to isortptr. (6 points)

Practice Program: Add a function to isort.c to perform a pointer-based array printing (along the lines of isortptr) called print_array_ptr. (4 points)

Submission

Please submit all required files as email attachments to terescoj AT strose.edu. You are recommended to do so by Tuesday, January 7, 2014. Be sure to check that you have used the correct file names and that your submission matches all of the submission guidelines listed on the course home page.