UMBC CS 201, Spring 02
UMBC CMSC 201 Spring '02 CSEE | 201 | 201 S'02 | lectures | news | help

A Combined Example

This program will work with right triangles. We have a data file that gives the lengths of the two sides of right triangles and we are to calculate the hypotenuse of each triangle. The first item in the data file is the number of pairs of sides that exist in the file.

The Data File

linux1[520] cat triangles.dat 5 3.000 4.000 3.250 5.750 4.500 7.250 5.000 8.000 6.000 8.000 linux1[521] Our program will open the file and read the number of pairs and then allocate enough memory to hold an array of that many TRIANGLE structures. We can then read the lengths of the sides into each of the structures, calculate the hypotenuse for each, and later print it all out in a chart.

The Program

/********************************* ** File file_malloc.c ** Author: S. Bogar ** Date: 04/03/02 ** Section: 101 ** SSN: 123-45-6789 ** E-Mail: bogar@cs.umbc.edu ** ** This file demonstrates file handling, dynamic ** memory allocation and working with an array of ** structures. *******************************/ #include <stdio.h> #include <stdlib.h> #include <math.h> typedef struct triangle { float sideA; float sideB; float hypotenuse; } TRIANGLE; int main() { int i, items ; TRIANGLE *triangles; FILE *ifp; /* open the data file */ ifp = fopen("triangles.dat", "r"); if (ifp == NULL) { printf("Couldn't open triangles.dat\n"); exit(-1); } /* read the number of items from the file */ fscanf(ifp, "%d", &items); /* Get a block of memory big enough to hold that many TRIANGLES */ triangles = (TRIANGLE *) malloc(items * sizeof(TRIANGLE)) ; if(triangles == NULL) { printf("Not enough memory\n"); exit(-2); } /* Lets use it as an array of TRIANGLES and fill the values of all the sideAs and sideBs by reading them from the file */ for(i = 0; i < items; i++) { fscanf(ifp, "%f", &triangles[i].sideA); fscanf(ifp, "%f", &triangles[i].sideB); } /* Close the file since we're finished reading from it */ fclose(ifp); /* Calculate the hypotenuse */ for (i = 0 ; i < items ; i++) { triangles[i].hypotenuse = sqrt(triangles[i].sideA * triangles[i].sideA + triangles[i].sideB * triangles[i].sideB ); } /* Print out the results */ printf("\n\tSide A\t\tSide B\t\tHypotenuse\n\n"); for (i = 0 ; i < items ; i++) { printf("\t%6.3f\t\t%6.3f\t\t%6.3f\n", triangles[i].sideA, triangles[i].sideB, triangles[i].hypotenuse); } printf("\n"); /* Give up use of the memory block */ free(triangles) ; return 0; }

The Sample Run

linux1[519] a.out Side A Side B Hypotenuse 3.000 4.000 5.000 3.250 5.750 6.605 4.500 7.250 8.533 5.000 8.000 9.434 6.000 8.000 10.000 linux1[520]


CSEE | 201 | 201 S'02 | lectures | news | help

Last Modified - Wednesday, 03-Apr-2002 18:48:35 EST