EXERCISES ON POINTERS




 1. What's the difference between the following declarations.

         A.  int *x;
         B.  int* x;
         C.  int * x;

 2. 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;
        }

 3. 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;
        }


 4. 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;
        }

 5. Assume int x[5] = {0, 1, 2, 3, 4}.  What are the values of x after calling
    swap2(x+1, x+4)?

 6. 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]);
        }

 7. 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?

 8. What is the difference between the following two function:

       int middle1(int a[], int n) {      int middle2(int *a, int n) {
          return a[n/2];                     return a[n/2];
       }                                  }

 9. 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?