EXERCISES ON POINTERS READING ------- Kernighan and Ritchie, 5.1-5.3 King, Chapter 11 (Pointers) Chapter 12.1-12.3 (Pointers and arrays) SUPPLEMENTAL READING -------------------- Deitel and Deitel, 7.1-7.4 7.7-7.8 EXERCISES --------- 0. What's the difference between the following declarations. A. int *x; B. int* x; C. int * x; 1. Assume x = 5, y = 10. What are the values of x and y after calling swap1(x, y)? void swap1(int a, int b) { int t; t = a; a = b; b = t; } 2. Assume x = 5, y = 10. What are the values of x and y after calling swap2(&x, &y)? void swap2(int *pa, int *pb) { int t; t = *pa; *pa = *pb; *pb = t; } 3. Assume int x[5] = {0, 1, 2, 3, 4}. What are the values of x after calling swap3(x, 1, 4)? void swap3(int a[], int i, int j) { int t; t = a[i]; a[i] = a[j]; a[j] = t; } 4. Assume int x[5] = {0, 1, 2, 3, 4}. What are the values of x after calling swap2(x+1, x+4)? 5. Assume int x[5] = {0, 1, 2, 3, 4}. What does print3(&x[0]) print? print3(&x[2])? print3(&x[4])? void print3(int x[]) { int i; for (i = 0; i < 3; i++) printf("%d ", x[i]); } 6. When we pass an array to a function in C, it passes a pointer to the 0th array element instead. Why doesn't C just create a new local copy of the array, as it does with integers? 7. What is the difference between the following two functions int middle1(int a[], int n) { int middle2(int *a, int n) { return a[n/2]; return a[n/2]; } } 8. To print an integer n to standard output we use printf("%d", n), but to read it in we use scanf("%d ", &n). Why is the & necessary with scanf? . . . . ANSWERS TO EXERCISES ON POINTERS 0. None. Some people prefer A to indicate that *x is an int; thus x is a pointer to an int. Others prefer B to indicate that x is the variable being declared. Not many people use C; it was just included to demonstrate that the position of the * is irrelevant. 1. x = 5, y = 10. The function has no effect since integers are passed by value. Variables a and b contain only local copies of the integers 5 and 10. 2. x = 10, y = 5. Since the memory addresses of x and y are passed, the function is able to correctly swap their values. 3. x = {0, 4, 2, 3, 1}. The memory address of the 0th array element of a is passed to the function. 4. x = {0, 4, 2, 3, 1}. Address arithmetic says that a+1 is the memory address of the 1st array element and a+4 is a pointer to the 4th. 5. 0 1 2 Same as print3(a). 2 3 4 Same as print3(a+2). Just like array starts at element 2. 4 ? ? Out of bounds access. 6. Efficiency. Arrays can have billions of elements. The overhead of copying them each time you call a function would be overwhelming. It also means that you can pass a "subarray" to a function for processing as in the previous question. 7. None. It is a matter of style. Beginners usually prefer the first. 8. scanf needs to change the value of n. A function cannot change the value of an integer unless it knows its memory address. Instead of passing the current value of n, we use &n to pass its memory address.