Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!swrinde!zaphod.mps.ohio-state.edu!wuarchive!udel!haven!decuac!hadron!rlgvax!scc From: scc@rlgvax.UUCP (Stephen Carlson) Newsgroups: comp.lang.c Subject: Re: Is there a good example of how toupper() works? Message-ID: <1353@rlgvax.UUCP> Date: 17 Oct 90 14:35:02 GMT References: <2466@ux.acs.umn.edu> Reply-To: scc@rlgvax.OPCR.ICL.COM (Stephen Carlson) Organization: ICL North America, OFFICEPOWER Products Center, Reston, VA Lines: 69 In article <2466@ux.acs.umn.edu> edh@ux.acs.umn.edu (Eric D. Hendrickson) writes: >Basically, what I want to do is take a string of upper/lower case, and make >it all upper case. Here is a first try at it, > > >#include >main() >{ > char *duh = "Hello"; > printf("%s\n", duh); > while (*duh <= strlen(duh)) { > if (islower(*duh)) *duh = toupper(*duh); > *duh++; > } > printf("%s\n", duh); >} Since others have pointed out the problem with the while loop condition, I would like to point out that with a declaration of char *duh = "Hello"; the compiler is free to put this string in read-only memory (text). Then the subsequent if (...) *duh = toupper(*duh); will dump core with a segmentation violation (SIGSEGV). You may have lucked out since the incorrect loop condition avoids this statement. I would recommend declaring `duh' as a (static) array and then using a pointer to do the work on the array: #include #include int main() { static char duh[] = "Hello"; char *p = duh; printf("%s\n", duh); while (*p) { /* or (*p != '\0') if that is your style */ if (islower(*p)) *p = toupper(*p); p++; } printf("%s\n", duh); return 0; } Notes: Declaring a char array and initializing it to a string will copy it to a writable area. It might even be more efficient. On some systems, toupper() is safe to use even if the char is not a lower case letter. On other systems, the islower() test is necessary. ANSI standardizes this. The expression `*duh++' will increment the pointer as you want, but it will do a useless deference (hence lint's "null effect"). In no case will it increment the char it points to as others incorrectly state. By the way, the new program lints (ignoring the frivolous "returns a value that is always ignored" message) and runs with no problem. -- Stephen Carlson | ICL OFFICEPOWER Center scc@rlgvax.opcr.icl.com | 11490 Commerce Park Drive ..!uunet!rlgvax!scc | Reston, VA 22091