prev

Structure Example

next

Source code
     #include <stdio.h>
     #include <string.h>
     
     /*
      * Program to create instances of the particles structure
      */
     
     /* particle structure definition */
     struct particle_type {
       double pos [3];
       double mass;
       int type;
       char name [80];
     };
     
     int main ( void )
     {
       /* create an array of three particle structures */
       struct particle_type particles [3];
     
       /* assign values to the first structure in the array */
       particles[0].pos[0] = 1.1;
       particles[0].pos[1] = 2.2;
       particles[0].pos[2] = 3.3;
       particles[0].mass = 14.2;
       particles[0].type = 1;
       strcpy ( particles[0].name, "neutron" );
     
       printf ( "%s (type %d): (%.2f, %.2f, %.2f), mass %.1f\n", particles[0].name,
                particles[0].type, particles[0].pos[0], particles[0].pos[1],
                particles[0].pos[2], particles[0].mass );
     
       /* copy the values from the first structure into the second and change
        * the places that matter 
        */
       particles[1] = particles[0];
       particles[1].type++;
       strcpy ( particles[1].name, "proton" );
     
       printf ( "%s (type %d): (%.2f, %.2f, %.2f), mass %.1f\n", particles[1].name,
                particles[1].type, particles[1].pos[0], particles[1].pos[1],
                particles[1].pos[2], particles[1].mass );
     
       /* again copy the first one to initialize this one */
       particles[2] = particles[0];
       particles[2].type += 2;
       strcpy ( particles[2].name, "electron" );
     
       printf ( "%s (type %d): (%.2f, %.2f, %.2f), mass %.1f\n", particles[2].name,
                particles[2].type, particles[2].pos[0], particles[2].pos[1],
                particles[2].pos[2], particles[2].mass );
     
       return ( 0 );
     }

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