Itzik984 Itzik984 - 2 months ago 16
C Question

Uppercase in C language

I have this code:

void changeToCapital(char* str)
{
int i;
for (i=0; i<strlen(str); i++)
{
str[i] =str[i] -32;
}
}


and this method is supposed to get a
char*
variable, and change it to its uppercase. For some reason I'm getting an error saying
EXECUTE_BAD_ACCESS
.

The calling function:

char* s = "itzik";
changeToCapital(s);
printf("%s\n",s);


What am I doing wrong here?

Answer

This is most likely because you are passing it a pointer to non-writable memory, such as one obtained from a string literal:

char *ptr = "Hello";
changeToCapital(ptr); // <<== ERROR !

You can change the call to avoid the error:

char ptr[] = "Hello";
changeToCapital(ptr);

On a side note, your change to upper case works only when all letters are in the lower case. You should use toupper(ch) function instead of subtracting 32.

void changeToCapital(char* str) {
    for (; *str = toupper(*str) ; str++)
        ;
}