Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the program ?

#include <stdio.h>

int main()
{
    static int arr[] = {0, 1, 2, 3, 4};
    int *p[] = {arr, arr+1, arr+2, arr+3, arr+4};
    int **ptr=p;
    ptr++;
    printf("%d, %d, %d\n", ptr-p, *ptr-arr, **ptr);
    *ptr++;
    printf("%d, %d, %d\n", ptr-p, *ptr-arr, **ptr);
    *++ptr;
    printf("%d, %d, %d\n", ptr-p, *ptr-arr, **ptr);
    ++*ptr;
    printf("%d, %d, %d\n", ptr-p, *ptr-arr, **ptr);
    return 0;
}

 

  • A.0, 0, 0
    1, 1, 1
    2, 2, 2
    3, 3, 3
  • B.1, 1, 2
    2, 2, 3
    3, 3, 4
    4, 4, 1
  • C.1, 1, 1
    2, 2, 2
    3, 3, 3
    3, 4, 4
  • D.0, 1, 2
    1, 2, 3
    2, 3, 4
    3, 4, 5

Answer: C

Correct answer: 1, 1, 1
2, 2, 2
3, 3, 3
3, 4, 4

p holds the five addresses arr … arr+4, and ptr walks along p. Take the four statements in turn.

  • ptr++ - ptr = p+1. Then ptr-p is 1, *ptr-arr is 1, **ptr is arr[1] = 1 → 1, 1, 1
  • *ptr++ - the ++ binds to ptr, and the dereference is thrown away, so ptr = p+2 → 2, 2, 2
  • *++ptr - again only ptr moves, to p+3 → 3, 3, 3
  • ++*ptr - here the increment applies to *ptr, that is to p[3], which becomes arr+4. ptr itself has not moved → ptr-p = 3, *ptr-arr = 4, **ptr = arr[4] = 4 → 3, 4, 4

The point of the question is that the last line increments what the pointer points to, while the three before it increment the pointer.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.