Uppercase in C language

点点圈 提交于 2019-12-24 07:48:40

问题


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?


回答1:


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



回答2:


First:

You are constantly calculating strlen. Instead, you should store the length of the string in a local variable.

Second: you are probably calling the function like this:

char *str = "Hello World";
changeToCapital(str);

This is BAD. "Hello World" is const, and cannot be modified by your program. Instead, you should specify your string as a character array, to ensure that it is immutable:

char str[] = "Hello World";
changeToCapital(str);


来源:https://stackoverflow.com/questions/10689876/uppercase-in-c-language

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!