Note: Questions 1-3 are taken from the King book, pg. 218 1. If i is a variable and p points to i, which of the following expressions are aliases for i? (a and g) What is the meaning of each expression? int i = 10; a) *p - 10 b) &p - address of p c) *&p - address of i (dereference the address of p) d) &*p - address of i (get the address of what p points to) e) *i - Error 'unary *' f) &i - address of i g) *&i - 10 h) &*i - Error 'unary *' NOTE: In general you shouldn't have to write code that uses constructions like c, d, g and h since they are either erroneous or can be done in a more straight-forward fashion ex. can use a) instead of g) 2. If i is an int variable and p and q are pointers to int, which of the following assignments are legal? int i = 20; a) p = i; warning: assignment makes pointer from integer without a cast p holds 20 or 0x14 which is not a valid address. b) *p = &i; warning: assignment makes integer from pointer without a cast the location p points to gets the value of the address of i i == address of i now. c) &p = q; Error invalid lvalue (Can't change the address of p) d) p = &q; warning: assignment from incompatible pointer type the address of q is not of type pointer-to-int e) p = *&q; okay - p gets the value of q. f) p = q; okay and much better syntax g) p = *q; p is assigned what q points to. (q was not initialized) h) *p = q; warning: assignment makes integer from pointer without a cast i) *p = *q; 3. What are the errors in this code? void avg_sum(double a[], int n, double *avg, double *sum) { int i; sum = 0.0; for(i = 0; i < n; i++) sum += a[i]; avg = sum / n; } Solution: void avg_sum(double a[], int n, double *avg, double *sum) { int i; *sum = 0.0; for(i = 0; i < n; i++) *sum += a[i]; *avg = *sum / n; } Why would I pass in avg and sum as pointers? (We want to change their values, and C uses pass-by-value for function arguments.) How would I call avg_sum? double x[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; double sum; double avg; avg_sum(x, 10, &avg, &sum); Why is the following incorrect? double x[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; double *sum; double *avg; avg_sum(x, 10, avg, sum); (sum and avg not initialized -- they don't point to declared double variables) 4. Our own simple implementation of strcpy: char * mystrcpy(char *a, char *b) { int i = 0; while( b[i] != '\0') { a[i] = b[i]; i++; } a[i] = '\0'; return a; } What kind of error checking could we do? (We could check if a or b are NULL, but we can't do much else.) NOTE: We could run into problems if we call mystrcpy and the array pointed to by b is not NULL terminated (we will keep assigning values to a until we eventually hit '\0' -- buffer overflow potential!)