All pastes #465014 Raw Edit

Stuff

public c v1 · immutable
#465014 ·published 2007-04-29 21:26 UTC
rendered paste body
/* * SelfTest.question3.c * Chapter 11 * 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 <stdio.h>void copystr(char *, char * ); //prototype: takes 2 char pointers, returns nothingint 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  // ron - i still think this declares a char* called "bb" and points it to a 0-length array - that array, i'm pretty sure, is  // not the same length as "aa" - check to see if sizeof(aa) returns 17 - i bet it returns 4 (32-bit pointer).  what you mean   // is strlen(aa) (which counts forward until it finds a \0)  // since "bb" points to a 0-length array, when you start writing into it it's basically overwriting the other elements in the  // stack - you must either allocate an array as big as the source array to hold the copy or dynamically allocate the memory  // using alloc() (or one of its variations) and then make sure to call free() on the array when you're done (the cost of using  // heap-space is that you have to tell the system when you're done with it if you want to avoid memory leaks)  char bb[ sizeof(aa) ]={};        // declare char array of equal size, and initialize empty  char *paa, *pbb ;     // declare 2 char pointers  paa=aa;    // initialize char pointer to &aa[], using shorthand aa.  pbb=bb;    // initialize char pointer to &bb[], 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{  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");}