#include <stdio.h> struct Bulb { int watts; int lumens; }; #define length 10 /* function to print a Bulb array */ void printArray( struct Bulb b[], int size ) { int j; for ( j=0; j<size; j++ ) printf("bulb %2d watts = %d\tlumens = %d\n", j, b[j].watts, b[j].lumens ); } int main() { /* declare an array of 10 Bulbs */ struct Bulb lights[length] = { {100,1710}, {60,1065}, {50,800}, {30,500}, {15,250} }; printArray(lights, length); return 0; }
When there is an initializer, the first bulbs in the array are initialized to the values specified. The remaining bulbs are initialized to zero. If there is no initializer, then no bulbs are initialized.
The parameter b
in the function is actually the address
of the array.
The corresponding argument lights
in the function call is also
an address (a pointer).
When the function is called, no copy is made of the array.
The function accesses the array's data through the pointer.
The syntax of arrays makes this easy to do, but obscures the fact that it is happening.
Remember that the name of an array (here, lights
) stands for its address,
so the call
printArray(lights, length);
passes the address of the array to printArray()
.
Inside the function, the expression
b[j].watts
accesses the array through its address, b
.