runner% cat params.c /* params.c: test 3 ways for a function to give a value */ /* to a string */ /* Written by NR Wagner, 3 Mar 1997 */ #include #include #include void f1(char *word); char *f2(void); void f3(char **wordptr); void main(void) { char word1[20]; char *word2; char *word3; f1(word1); printf("1st method: ""%s""\n", word1); word2 = f2(); printf("2nd method: ""%s""\n", word2); f3(&word3); printf("3rd method: ""%s""\n", word3); } /* f1: caller supplies storage */ /* function inserts characters. */ void f1(char *word) { strcpy(word, "Alferd Packer"); } /* f2: caller supplies pointer to char */ /* function allocates storage, inserts chars, */ /* and returns pointer to the storage. */ char *f2(void) { char * word; word = (char *) malloc(20); strcpy(word, "Alf Landon"); return word; } /* f3: caller supplies pointer to string */ /* function allocates storage, inserts chars, */ /* and returns pointer to the storage via the */ /* parameter. */ void f3(char **wordptr) { char *word; word = (char *) malloc(20); strcpy(word, "Alfred E. Newman"); *wordptr = word; } runner% lint -m -u params.c function returns value which is always ignored strcpy printf runner% cc -o parmas params.c runner% params 1st method: Alferd Packer 2nd method: Alf Landon 3rd method: Alfred E. Newman runner%