/*********************************************************************** Kenneth L Moore CIT 145 22/01/02 07:23 file strsc.c This program demonstrates string basics Note that there is really no 'string' data type in C. Strings are implemented as char arrays. The end of a string is indicated by a null (hex 00) byte. This can be placed before the end of the char array. Because of this byte, always allow for one extra char of storage. The C compiler does not (as in many other error cases) flag statements that store beyond the end of a char array. These errors can corrupt storage and cause program failure. Such errors are a common source of hacker attacks: for example the buffer overflow attach to take control of the computer. The programmer must be careful to avoid these out-of-bounds errors and out-of-bounds array errors in general. Strings can be manipulated as arrays, processing with subscripts. There are, also, many library string functions. ***********************************************************************/ #include #include #include // needed for msvc++ /* This prototype allows the compiler to find the function (function definitions must be placed before where they are used) and allows me to actually implement the function at the end of main. */ void stro( char *str, int strlen, char *name ); /* macro to invoke string display with length and name */ #define SHOWSTR( s ) stro( (s), sizeof( (s) ), #s ) int main() { int mm; int i; // note: the initilization for str1, str2, str5 can cause problems // depending on the compiler. Explicit sizing is safer. char str1[] = "12345"; /* 6 bytes, 1-2-3-4-5- */ char str2[] = { 'H', 'e', 'l', 'l', 'o' }; /* 5 bytes, h-e-l-l-o */ char str3[15] = "Hello,\nworld!"; char str4[21] = "abcdefghijklmnopq"; char *str5 = "Where is this allocated?"; char *str6; str6 = (char *)malloc(256);// in C++ use new strcpy(str6,"I know where this was allocated"); SHOWSTR( str1 ); SHOWSTR( str2 ); SHOWSTR( str3 ); str3[0] = 'Y'; /* overlay 1st four character of str3 */ str3[1] = 'e'; str3[2] = 's'; str3[3] = '\0'; SHOWSTR( str3 ); /* can't do this: str3 = "Kenco". Have to use strcpy ... */ strcpy( str3, "Kenco" ); SHOWSTR( str3 ); SHOWSTR( str4 ); /* some letters */ str4[6] = '\0'; /* terminate early with a null */ SHOWSTR( str4 ); str4[6] = '+'; /* replace the null */ SHOWSTR( str4 ); for( i = 5; i < sizeof( str4 ) - 1; i++ ) { str4[i] = '*'; /* fill positions 6 - 30 */ } str4[i] = 0; SHOWSTR( str4 ); SHOWSTR( str5 ); SHOWSTR( str6 ); free(str6); // in C++ use delete // hold DOS window scanf("%d",&mm); return( 0 ); } /* routine to display string contents */ void stro( char * str, int strmax, char *name ) { int i; printf( "sizeof(%s)=%d\n", name,strmax ); printf( "contents " ); for( i = 0; i < strmax; i++ ) { printf( ( ( str[i] < ' ' ) ? "[x%0.2x]" : "[%c]" ), str[i] ); } printf( "\nPrints as <%s>\n\n", str ); }