/* * ===================================================================== * argalloc.c -- demonstrate use of string functions * * Copyright (C) 1998 by Mark Austin and David Chancogne. * * 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 * ===================================================================== */ #include #include int main( void ) { enum { MaxString = 20 }; /* allocate enough for long string */ char caString[MaxString] = "myfile"; /* compile-time allocation */ char* cpStringExt = ".dat"; /* point to extension */ char caNewExtension[MaxString]; /* read in at run time */ char* cpNew; /* assigned dynamically below */ /* [a] : copy the extension referred to by cpStringExt onto the end of */ /* the string contained in (ultimately referred to by) caString */ strcat( caString, cpStringExt ); printf( "\nThe concatenated file name is %s\n", caString ); /* [b] : reset caString to its original state ("myfile") */ strcpy( caString, "myfile" ); /* [c] : dynamically request a new file extension */ printf( "\nEnter another file extension (<20 characters long):" ); scanf( "%s", caNewExtension ); /* [d] : dynamically allocate the necessary space at run time */ cpNew = (char*) malloc( strlen(caString) + strlen(caNewExtension) + 1 ); if( NULL == cpNew ) { /* allocation failure */ printf("\n"); printf("Memory allocation failure in file %s, line %i\n", __FILE__, __LINE__ ); return 1; } /* [e] : copy in source string and concatenate the extension */ strcpy( cpNew, caString ); strcat( cpNew, caNewExtension ); printf( "\nThe concatenated file name is %s\n", cpNew ); return 0; }