Is there a good example of how toupper() works?

Stephen Carlson scc at rlgvax.UUCP
Thu Oct 18 00:35:02 AEST 1990


In article <2466 at ux.acs.umn.edu> edh at 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 <ctype.h>
>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 <stdio.h>
#include <ctype.h>

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 at rlgvax.opcr.icl.com    | 11490 Commerce Park Drive
..!uunet!rlgvax!scc        | Reston, VA  22091



More information about the Comp.lang.c mailing list