Itzik984 Itzik984 - 11 months ago 73
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
variable, and change it to its uppercase. For some reason I'm getting an error saying

The calling function:

char* s = "itzik";

What am I doing wrong here?

Answer Source

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";

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++)