我在C中编写自己的ToLower(char*str)实现.但是我在函数中遇到了分段错误.我写的功能是:
void ToLower(char *str)
{
while(*str != '\0')
{
if(*str >=65 && *str<=90)
{
// It fails in the below assignment
*str = *str + 32;
}
str++;
}
}
Run Code Online (Sandbox Code Playgroud)
abe*_*nky 10
当你把它称为时,你几乎肯定会失败:
int main(void)
{
ToLower("HelloWorld");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是因为它"HelloWorld"是一个文字的常量字符串,您无法更改其内容.
尝试改为:
int main(void)
{
char str[] = "HelloWorld";
// Now str is your own local buffer, that you can modify.
// It is initialized with the text, but that text can be changed.
ToLower(str);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
通常认为在对字符串进行操作的函数中接受长度参数是一种很好的形式。这样,如果您传入一个非空终止的字符串,该函数将不会循环超过输入的末尾。
您可以使用调试器单步执行函数调用,或者在循环中添加打印语句并查看它迭代了多少次。
| 归档时间: |
|
| 查看次数: |
6313 次 |
| 最近记录: |