G05 Answer


#include <stdio.h>

struct Bulb
{
  int watts;
  int lumens;
};

/* function to print a Bulb */
void printBulb( struct Bulb b )
{
  printf("watts = %d\tlumens = %d\n", b.watts, b.lumens );
}

int main(int argc, char *argv[])
{
  int j;
  
  /* declare an array of 10 Bulbs */
  struct Bulb lights[10] ;
  
  /* zero all Bulbs */
  for ( j=0; j<10; j++ )
  {
    lights[j].watts = 0; lights[j].lumens = 0;
  }
    
  /* initialize several Bulbs */
  lights[0].watts = 100; lights[0].lumens = 1710;
  lights[1].watts =  60; lights[1].lumens = 1065;
   
  /* print values of Bulbs */
  for ( j=0; j<10; j++ )
  {
     printf("Bulb %2d: ", j );
     printBulb( lights[j] );
  }  
    
  system("PAUSE");	
  return 0;
}

Comments: If the array is declared as a local variable (as it is in the above program) it will not be initialized and the values of the members will be unpredictable. If the array is declared outside of any function, it will be allocated in static memory and will be automatically initialized to zero:

#include <stdio.h>

struct Bulb
{
  int watts;
  int lumens;
};

struct Bulb lights[10] ;

void printBulb( struct Bulb b )
{...}

int main(int argc, char *argv[])
{...}

Another way to initialize the first several elements is by using an initialization list:

struct Bulb lights[10] = { {100,1710}, {60,1065} };

Here, the first two elements of the array are initialized to the given values and the remaining elements are initialized to zero.