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

Discussion

If the size of integer is 4bytes, What will be the output of the program?

#include <stdio.h>

int main()
{
    int arr[] = {12, 13, 14, 15, 16};
    printf("%d, %d, %d\n", sizeof(arr), sizeof(*arr), sizeof(arr[0]));
    return 0;
}

 

  • A.10, 2, 4
  • B.20, 4, 4
  • C.16, 2, 2
  • D.20, 2, 2

Answer: B

Correct answer: 20, 4, 4

sizeof(arr) gives the size of the whole array - five elements of four bytes, so 20. It is one of the few contexts in which an array name does not decay to a pointer.

*arr is the first element, an int, so its size is 4; and arr[0] is the same object written differently, so it too is 4. The pair is worth noting because sizeof(arr)/sizeof(arr[0]) is the idiomatic way to count an array's elements - and it fails silently once the array has decayed to a pointer.

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

Post your comment

Please log in or register to post a comment.