Answer T5

array of 10 bulb structs
#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 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] );
  }  
    	
  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. However, an the initial values of an array can be specified in an initializer list (see below). 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()
{...}

Another way to initialize the first several elements is by using an initializer 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.



Back to Puzzle Home