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

Discussion

What is the output of the following C program?

#include \(\lt\)stdio.h\(\gt\)
int main() {
  double a[2]={20.0, 25.0}, *p, *q;
  p = a;
  q = p + 1;
  printf("%d,%d", (int)(q - p), (int)(*q - *p));
  return 0;}

  • A.4,8
  • B.1,5
  • C.8,5
  • D.1,8

Answer: B

The output is 1,5.

p points to a[0] and q to a[1]. Subtracting two pointers into the same array gives the number of elements between them, not the number of bytes, so q - p is 1 even though a double occupies 8 bytes.

*q - *p subtracts the values stored there, \(25.0 - 20.0 = 5.0\), and the cast to int gives 5. Both arguments are ints, so the %d conversions print 1,5.

8 (in 8,5) is the byte distance, which pointer subtraction does not return. 4,8 and 1,8 mix up the element and byte counts, and the value difference is 5, never 8.

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

Post your comment

Please log in or register to post a comment.