6.30 Linked lists6 Notes6.28 String Functions6.29 Structures

6.29 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 available 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;
        /* Place 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: Louis Taber, louis.taber.at.pima at gmail dot com (520) 206-6850
My web site in Cleveland, OH
The Pima Community College web site

6.30 Linked lists6 Notes6.28 String Functions6.29 Structures