CISC220 Spring 2010 James Atlas Lecture 04: Pointers, Functions, Memory Management, ADTs, Classes, Hardware, Software, Graphics, Networking, AI, Databases, Scientific Computing, Parallel Architectures
Question 4 What is output from the following code: void swap(int x, int y) { int temp = x; x = y; y = temp; } int main(void) { int a = 0; int b = 5; swap(a,b); cout << a << endl; }
Question 5 Change the code to work correctly using references: void swap(int x, int y) { int temp = x; x = y; y = temp; } int main(void) { int a = 0; int b = 5; swap(a,b); cout << a << endl; }
Question 6 What is the value of temp after each assignment? char blocks[3] = {'A','B','C'}; char *ptr = &blocks[0]; char temp; /*1*/ temp = blocks[0]; /*2*/ temp = *(blocks + 2); /*3*/ temp = *(ptr + 1); ptr = blocks + 1; /*4*/ temp = *ptr; /*5*/ temp = *(ptr + 1);
Question 7 What is the value of temp after each assignment? char blocks[3] = {'A','B','C'}; char *ptr = blocks; char temp; /*1*/ temp = *++ptr; /*2*/ temp = ++*ptr; /*3*/ temp = *ptr++; /*4*/ temp = *ptr;
Question 8 Write code to reverse a string using only pointer arithmetic (no array accessors): int main(void) { char s[10] = "abcde"; for (int i = 0; s[i] != NULL; i++) { cout << s[i]; } reverseString(s); for (int i = 0; s[i] != NULL; i++) { cout << s[i]; } cout << endl; return 0; }
Question 9 What is output from the following code ? int *x, *y, *z; x = new int[20]; x[10] = 0; y = x; x[10] = 5; cout << x[10] << ", " << y[10] << endl; x[10] = 15; z = new int[10]; for (int i = 0; i < 10; i++) z[i] = x[i]; z[10] = 25; cout << x[10] << ", " << y[10] << ", " << z[10] << endl;
Structs Combined data struct Fraction { int numerator; int denominator; }; Fraction **fractions; // What is this?
Classes Reading - K+W Chap ,
Abstract Data Types (ADTs) Combination of data and operations Encapsulates implementation details Provides an interface for usage
ADT Example A mathematical set of integers, S Four operations –add(x) where x is an integer –remove(x) removes integer x from the set –contains(x) returns true if the set contains x –size() returns the number of elements in the set No implementation details! –The actual set could be implemented using an array, a linked list, a hashtable, or even a web blog (although posting/parsing a web blog for a simple integer would be very innefficient!)
C++ Classes One way to represent ADTs Header file specifies the interface Class file encapsulates the implementation