问题
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