prev

Typedef Example

next

Source code
     #include <stdio.h>
     #include <string.h>
     
     /*
      * Program to create instances of the particles structure
      */
     
     /* valid particle types */
     enum { NEUTRON, PROTON, ELECTRON };
     char *names [] = { "neutron", "proton", "electron" };
     
     /* define a vector as a 3D double */
     typedef double vector [3];
     
     /* define a string as a character array */
     typedef char string [80];
     
     /* eliminate the need to say struct all over the place */
     typedef struct {
       vector pos;
       double mass;
       int type;
       string name;
     } particle;
     
     /* function declarations */
     particle initParticle ( int type );
     void printParticle ( particle );
     
     
     int main ( void )
     {
       /* create an array of three particle structures */
       particle particles [3];
     
       /* call the initParticle to initialize these particles */
     
       particles [NEUTRON] = initParticle ( NEUTRON );
       printParticle ( particles [NEUTRON] );
     
       particles [PROTON] = initParticle ( PROTON );
       printParticle ( particles [PROTON] );
     
       particles [ELECTRON] = initParticle ( ELECTRON );
       printParticle ( particles [ELECTRON] );
     
       return ( 0 );
     }
     
     /*
      * Return an initialized particle based on the enumerated type of the 
      *  argument
      */
     particle initParticle ( int type ) {
       /* create a particle structure and set values in it */
       particle p;
     
       p.pos[0] = 1.1;
       p.pos[1] = 2.2;
       p.pos[2] = 3.3;
       p.mass = 14.2;
     
       p.type = type;
       strcpy ( p.name, names[type] );
     
       /* return the newly initialized structure */
       return ( p );
     }
     
     /*
      * Print out the particle
      */
     void printParticle ( particle p ) {
       printf ( "%s (type %d): (%.2f, %.2f, %.2f), mass %.1f\n", p.name,
                p.type, p.pos[0], p.pos[1], p.pos[2], p.mass );
       return;
     }
     

Output:
neutron (type 0): (1.10, 2.20, 3.30), mass 14.2
proton (type 1): (1.10, 2.20, 3.30), mass 14.2
electron (type 2): (1.10, 2.20, 3.30), mass 14.2