5.31 Linked lists5 Notes5.29 String Functions5.30 Structures

5.30 Structures

Structures are a way of keeping related data together.

General form of a structure:

struct structure-name
 {
 field-type field-name
 field-type field-name
 field-type field-name
 ...
 } variable-name;

This program uses structures

The program: The source is avaliable at:
ftp://lt.tucson.az.us/pub/c/struct.c

/* Louis Taber    April 9, 2001
 *
 * Sample program for structures     */

#include <stdio.h>
#include <math.h>
        /* structure has a integer and a float */
struct twoitems
  {
  int a;
  float b;
  };
        /* Subroutine swaps values */
        /* doing type conversions  */
void swap(struct twoitems *subptr)
{
int temp;

temp = subptr->a;
subptr->a = (int)subptr->b;
subptr->b = (float)temp;
return;
}


main()
{       /* define x & y  using twoitems   */
        /* declaration                    */
 
struct twoitems x, y;
struct twoitems *ptr;
        /* initilize using dot syntax     */
x.a = 42;
x.b = 8.4;
        /* Plave values in y using x      */
y.a = (int)x.b + 1;
y.b = (int)sqrt((double)y.a);
        /* Print out structure y          */
printf("y:       %3d  %f\n", y.a, y.b);

        /* Allocate space for new structure */
ptr = (struct twoitems *)malloc( sizeof(struct twoitems) );
        /* Copy all of x into allocated space  */
*ptr = x;
        /* print copy pointed to by ptr        */
printf("copy:    %3d  %f\n", ptr->a, ptr->b);
        /* Call subroutine to swap elements    */
swap(ptr);
        /* print results of swap               */
printf("swapped: %3d  %f\n", ptr->a, ptr->b);

return 0;
}


And the output:

y:         9  3.000000
copy:     42  8.400000
swapped:   8  42.000000

Instructor: ltaber@pima.edu ** My new Home at GeoApps in Tucson ** The Pima College Site

5.31 Linked lists5 Notes5.29 String Functions5.30 Structures