retagged by
1,097 views
1 votes
1 votes

Pick the best statement for the below program:

#include "stdio.h"

int main()
{
 struct 
 {
     int a[2], b;
  } arr[] = {[0].a = {1}, [1].a = {2}, [0].b = 1, [1].b = 2};

 printf("%d %d %d and",arr[0].a[0],arr[0].a[1],arr[0].b);
 printf("%d %d %d\n",arr[1].a[0],arr[1].a[1],arr[1].b);

 return 0;
}

CHOOSE THE CORRECT ALTERNATIVE:

A

Compile error because struct type (containing two fields i.e. an array of int and an int) has been specified along with the definition of array arr[] of this struct type.

B

Compile error because of incorrect syntax for initialization of array arr[].

C

No compile error and two elements of arr[] would be defined and initialized. Output would be “1 0 1 and 2 0 2”.

D

No compile error and two elements of arr[] would be defined and initialized. Output would be “1 X 1 and 2 X 2” where X is some garbage random number.

retagged by

1 Answer

3 votes
3 votes

This is introduced in C99 standard called designated initializer.

 struct 
 {
     int a[2], b;
  } arr[] = {[0].a = {1}, [1].a = {2}, [0].b = 1, [1].b = 2};

This portion we can write as

 struct 
 {
     ....
  } 
  arr[0].a[0]=1
  arr[0].a[1]=0
  arr[0].b=1
  arr[1].a[0]=2
  arr[1].a[1]=0
  arr[1].b=2

In structure declaration , here are three elements. Array contains 2 elements and another integer b contains 1 element.

So, no compiler error will be there. Answer will be C)

Related questions