/* * =================================================================================== * test_readdata -- This program reads an unknown quantity of data from an input file. * -- We dynamically allocate memory for the data, and reallocate the * -- memory when more storage is needed. * =================================================================================== * Copyright (C) 1993-96 by Mark Austin and David Mazzoni. * * This software is provided "as is" without express or implied warranty. * Permission is granted to use this software on any computer system, * and to redistribute it freely, subject to the following restrictions: * * 1. The authors are not responsible for the consequences of use of * this software, even if they arise from defects in the software. * 2. The origin of this software must not be misrepresented, either * by explicit claim or by omission. * 3. Altered versions must be plainly marked as such, and must not * be misrepresented as being the original software. * 4. This notice is to remain intact. * Written By: Mark Austin July 1995 * =================================================================================== */ #include #include #include "miscellaneous.h" /* declarations for vector functions */ void VectorPrint( char *, float *, int ); int main( void ) { enum { InitialLength = 3, Increment = 2 }; float *fpData; float fDataPoint; int iNoPoints = 0; int iVectorLength; /* [a] : Allocate and print initial data vector */ fpData = (float *) safeCalloc( InitialLength, sizeof (float), __FILE__, __LINE__ ); iVectorLength = InitialLength; VectorPrint( "Initial data vector", fpData , iVectorLength ); /* [b] : Read data from standard input until an EOF is obtained */ while ( scanf( "%f%*c", &fDataPoint ) != EOF ) { iNoPoints = iNoPoints + 1; if( iNoPoints > iVectorLength ) { iVectorLength += Increment; fpData = (float *) realloc( fpData , iVectorLength*sizeof (float) ); assert ( fpData != (float *) NULL); VectorPrint( "Reallocated Data Vector", fpData , iVectorLength ); } fpData[ iNoPoints - 1 ] = fDataPoint; } VectorPrint( "Final Data Vector", fpData , iVectorLength ); /* [c] : Free vector memory */ free( (char *) fpData ); } /* * ================================================================ * VectorPrint() : Naive Implementation of Vector Print * * Input : char *cpMessage -- pointer to vector message. * float *fpVector -- pointer to float array * int iLength -- length of float array * Output : void. * ================================================================ */ void VectorPrint( char *cpMessage , float *fpVector , int iLength ) { int iRow; if(cpMessage != (char *) NULL) printf ("\nVECTOR \"%s\" \n\n", cpMessage ); else printf("\nVECTOR : \"UNTITLED\" \n\n"); for(iRow = 1; iRow <= iLength; iRow++) printf(" %3d %16.5e\n", iRow, fpVector[ iRow-1 ]); }