-4
  1. What is the output of the following code fragment?

int arr[5] = {1, 2, 3};
int *p1, *p2;
p1 = arr;
p2 = &arr[3];
printf("%d\n", (*p1)++ + --(*p2));

From my understanding, The first line initialises an array of 5 memory spaces and only fills positions 0,1 and 2. Then in the 3rd and 4th line, p1 points to the array position 0 and p2 points to array position 3 which is empty. So in line 5 when the question tries to print (*p1)++ + --(*p2), what will it print since p2 points to memory not containing any values?

Jim Lewis
  • 43,505
  • 7
  • 82
  • 96

1 Answers1

2

If there are fewer initializers than array elements, the extra array elements are initialized to zero.

This answer cites the relevant portion of the C99 standard:

The C and C++ standards guarantee that even if an integer array is located on automatic storage and if there are fewer initializers in a brace-enclosed list then the uninitialized elements must be initialized to 0.

C99 Standard 6.7.8.21

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

Community
  • 1
  • 1
Jim Lewis
  • 43,505
  • 7
  • 82
  • 96