/* * SelfTest.question3.c * Chapter 11 * By: John Stile * Purpose: Write a function named copystr that receives two pointers to arrays * of strings with the same size. * The first pointer str1 points to a string which has contents, * but str2 points to a blank array. */ #include void copystr(char *, char * ); //prototype: takes 2 char pointers, returns nothing int main(void) // header for main: takes nothing, returns int { // Setup the 2 arrays of equal size. // First array has content, second is empty char aa[]={"His name was John"}; // declare char array and initialize // First method // char bb[ sizeof(aa) ]={}; char bb[ sizeof(aa)/sizeof(aa[0]) ]={}; // declare char array of equal size, and initialize empty // without {}, initial print shows junk in the array. char *paa, *pbb ; // declare 2 char pointers paa=aa; // initialize char pointer to &aa[0], using shorthand aa. pbb=bb; // initialize char pointer to &bb[0], using shorthand bb. printf("Contents of array aa[]: %s\n", paa ); // print string starting at &aa[0] printf("Contents of array bb[]: %s\n", pbb ); // print string starting at &bb[0] printf("Calling function copystr.\n"); copystr( paa, pbb) ; // pass &aa[0] and &bb[0] to function copystr() printf("Contents of array bb[]: %s\n", pbb); return 0; } void copystr(char *str1, char *str2 ) //header: takes 2 addresses, // assigns to char pointers str1 and str2 // returns nothing { /* * First method * int ii; // declare int counter for( ii=0; *(str1+ii) ; ii++) // initialize coutner to 0 for first element // while the value at thing pointed to is not NULL // do block // then increment counter by 1 { *(str2+ii)=*(str1+ii); // assign the value at thing pointed to in first pointer // to the thing thing pointed to in second pointer } *(str2+ii)='\0'; // Add a null character at the end printf("End of function copystr.\n"); */ // K&R - Chpter 5.6 while( *str2++ = *str1++ ) // find what is as str2 and str1 // assign value at str1 to str2 // until null { ; } }