printf / output questions in C

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Thiengineer
    New Member
    • Feb 2007
    • 5

    printf / output questions in C

    Given the following code in C:

    Code:
     char *s[] = {"program","test","load","frame","stack",NULL};
     char **p = s + 2;
    Questions:

    a) printf{"%s",p[-2] + 3);

    b) printf("%c%s",* (s[1]),*p+1);

    c) printf("%c%c%c% c", **s+1, *(*(p-1)+1), *(*s+3)+2, *(p[-1]+strlen(p[-1])-1));

    d) *(*p+2) = '\0';
    strncat(*p,p[2],2);
    printf("%s",*p) ;


    My Answers:

    a) frame

    b) toad

    c) rea_ (the last character I don't know)

    d) lost


    Can someone verify if my answers are correct, if not please help me!

    THANK YOU!!
  • horace1
    Recognized Expert Top Contributor
    • Nov 2006
    • 1510

    #2
    I make the answers
    (a) gram
    (b) toad
    (c) qeit

    (d) causes a segmentation fault as the expression
    Code:
     *(*p+2) = '\0';
    attempts to change the 'a' in "load" to '\0' - "load" is a constant

    Comment

    • willakawill
      Top Contributor
      • Oct 2006
      • 1646

      #3
      a) is gram because p[-2] is a char* pointing to the 'p' in 'program'. Incrementing this pointer by 3 brings us to 'g'. printf will print all characters until the null character so we get 'gram'
      b) you are correct
      c) **s is the character 'p' and p + 1 is 'q'
      So we have 'q'

      (p - 1) is 'test'
      *(p - 1) is the char * pointing to 't'
      (*(p - 1)+1) increments the pointer by one character to 'e'
      *(*(p-1)+1) = 'e'
      So we have 'qe'

      *s is a char* pointing to 'p'
      (*s + 3) increments this pointer to point to 'g'
      *(*s + 3) is the char 'g'
      'g' + 2 = 'i' therefore *(*s+3)+2 = 'i'
      So we have 'qei'

      strlen(p[-1]) is the length of 'test' which is 4
      strlent(p[-1]) -1 is 4 - 1 = 3
      p[-1] is a char* pointing to 't'
      p[-1]+strlen(p[-1])-1 increments this char* by 3 to point to the last char in 'test' which is also 't'
      *(p[-1]+strlen(p[-1])-1) is the character 't'
      So we have 'qeit'

      Comment

      • Thiengineer
        New Member
        • Feb 2007
        • 5

        #4
        Thank you for all your help!

        I now understand a-c, but still uncertain about part d.

        I don't understand how there is a segmentation fault, if that is the case.

        Can someone please explain what's going on on part d?

        Thanks again!

        Comment

        • willakawill
          Top Contributor
          • Oct 2006
          • 1646

          #5
          You were correct in theory about the answer being 'lost' which is why I did not mention it. However, as Horace1 has pointed out, the code for part d raises an error. Perhaps you can get extra credits for pointing this out :)

          Comment

          Working...