CS140 Lecture notes -- A few pointer test programs

  • Jim Plank
  • Directory: ~cs140/www-home/notes/PointTest
  • Lecture notes: http://www.cs.utk.edu/~cs140/notes/PointTest
  • Thu Jan 28 10:21:26 EST 1999
    Here are a few little programs to test your knowledge of pointers. Go over them until you get them right, because they are all basic. You can go over them by copying them and the makefile to your directory and typing make, and then executing the programs.

    test1.c

    Suppose the first line of the following program prints ``s = 0xefffe4f8.'' What is the rest of the program's output?
    #include < stdio.h >
    
    main()
    {
      char s[15] = "Plank";
      int i;
      char *x;
    
      printf("s = 0x%x\n", s);
    
      for (i = 0; s[i] != '\0'; i++) {
        x = s + i;
        printf("i=%d  x=0x%x  x=%s  *x=%c  x-s=%d\n", i, x, x, *x, x-s);
      }
        
    }
    

    test2.c

    Suppose the first line of the following program prints ``s = 0xefffe4f0.'' What is the rest of the program's output?
    #include < stdio.h >
    
    main()
    {
      int s[5];
      int i;
      int *x;
    
      for (i = 0; i < 5; i++) {
        s[i] = 50 + i%2;
      }
    
      printf("s = 0x%x\n", s);
    
      for (i = 0; i < 5; i++) {
        x = s + i;
        printf("i=%d  x=0x%x  *x=%d  x-s=%d\n", i, x, *x, x-s);
      }
        
    }
    

    test3.c

    What is the output of the following program when the following lines are given as input?
    Jim Plank
    Tee Martin
    Sammy Sosa
    vols VOLS
    VOLS VOLS
    #include < stdio.h >
    
    char *smaller(char *s1, char *s2)
    {
      int i;
    
      i = strcmp(s1, s2);
      if (i < 0) return s1;
      if (i > 0) return s2;
      return NULL;
    }
    
    main()
    {
      char s1[100];
      char s2[100];
    
      while(1) {
        printf("Enter two words:\n");
        if (scanf("%s", s1) != 1) exit(0);
        if (scanf("%s", s2) != 1) exit(0);
        printf("Smaller is %s\n", smaller(s1, s2));
      }
    }
    

    test4.c

    What is the output of the following program when the following lines are given as input?
    Jim
      Jim
    Give     Him    Six!!
    #include < stdio.h >
    #include < string.h >
    
    char *word2(char *s1)
    {
      char *x;
    
      x = strchr(s1, ' ');
      if (x == NULL) return x;
      while (*x == ' ') x++;
      if (*x == '\0') return NULL;
      return x;
    }
    
    main()
    {
      char s1[100];
    
      while(gets(s1) != NULL) {
        for (x = s1; x != NULL; x = word2(x)) {
          printf("%s\n", x);
        }
      }
    }