UMBC CS 201, Fall 05
UMBC CMSC 201 Fall '05
CSEE | 201 | 201 F'05 | lectures | news | help

Structure Example

The Code

/************************************* ** File: structs.c ** Author: D. Frey ** Date: 1/24/00 ** Section: 0101 ** E-Mail: frey@cs.umbc.edu ** Modified by: Sue Evans ** Date: 2/29/04 ** Modified to meet current 201 standards ** ** This file demonstrates the basics of ** nested structures, the use of one structure ** within the definition of another. ***************************************/ #include <stdio.h> /* structure definitions */ /* a point with x- & y-coodinates */ struct point { int x; int y; }; /* a line defined by 2 points */ struct line { struct point startPoint; struct point endPoint; }; int main ( ) { struct line aLine; struct point point1, point2; struct point midPoint; /* initialize point1 */ point1.x = point1.y = 0; /* initialize point2 */ point2.x = 10; point2.y = 6; /* print the points */ printf ("\n"); printf ("Point1: (%d, %d)\n", point1.x, point1.y); printf ("Point2: (%d, %d)\n\n", point2.x, point2.y); /* calc and print midpoint between point1 & point2 */ midPoint.x = (point1.x + point2.x) / 2; midPoint.y = (point1.y + point2.y) / 2; printf ("The midpoint is (%d, %d)\n\n", midPoint.x, midPoint.y); /* now think of the line as a structure */ /* init the line by assigning the points */ aLine.startPoint = point1; aLine.endPoint = point2; /* change the x-coordinate of the endpoint */ aLine.endPoint.x = 8; /* print the line */ printf ("The line's startpoint: (%d, %d)\n", aLine.startPoint.x, aLine.startPoint.y); printf ("The line's endpoint: (%d, %d)\n", aLine.endPoint.x, aLine.endPoint.y); return 0; }

The Output

linux1[102] % a.out Point1: (0, 0) Point2: (10, 6) The midpoint is (5, 3) The line's startpoint: (0, 0) The line's endpoint: (8, 6)


CSEE | 201 | 201 F'05 | lectures | news | help

Sunday, 25-Sep-2005 10:38:55 EDT