C Programming language

adplus-dvertising
What is an Array ?
Previous Home Next

                                                                                     ARRAY OF STRUCTURES

 

Our sample program showing usage  of structure is rather simple minded. All it does is, it receives values into various structure elements and output these values. But that’s all we intended to do anyway...  show how structure types are created, how  structure variables are declared and how individual elements of a structure variable are referenced.

/* Usage of an array of structures */
main( )
{
struct book
{
char  name ;
float  price ;
int  pages ;
} ;

struct book  b[100] ;
int  i ;

for ( i = 0 ; i <= 99 ; i++ )
{
printf ( "\nEnter name, price and pages " ) ;
scanf ( "%c %f %d", &b[i].name, &b[i].price, &b[i].pages ) ;
}

for ( i = 0 ; i <= 99 ; i++ )
printf ( "\n%c %f %d", b[i].name, b[i].price, b[i].pages ) ;
}

linkfloat( )
{
float a = 0, *b ;
b = &a ;  /* cause emulator to be linked */
a = *b ;    /* suppress the warning - variable not used */
};

Now a few comments about the program: 

  1. Notice how the array of structures is declared.

       struct book b[100] ;

    This provides space in memory for 100 structures of the type struct book. 
     

  2. The syntax we use to reference each element of the array b is similar to the syntax used for arrays of  ints and  chars. For example, we refer to zeroth book’s price as  b[0].price. Similarly, we refer first     book’s pages as b[1].pages.
     

  3. In an array of structures all elements of the array are stored in adjacent memory locations. Since each element of this array is a structure, and since all structure elements are always stored in adjacent locations you can very well visualize the arrangement of array of structures in memory. In our example, b[0]’s  name,  price and  pages in memory would be immediately followed by b[1]’s name, price and pages, and so on.

     

  4. What is the function  linkfloat( ) doing here? If you don’t define it you are bound to get the error "Floating Point Formats Not Linked" with majority of C Compilers.  What causes this error to occur? When parsing our source file, if the compiler encounters a reference to the address of a float, it sets a flag to have the linker link in the floating-point emulator.  A floating point emulator is used to manipulate floating point numbers in runtime library functions like  scanf() and  atof( ). There are some cases in which the reference to the  float is a bit obscure and the compiler does not detect the need for the emulator. The most common is using  scanf( ) to read a  float in an array of structures as shown in our program.

     

Previous Home Next