C++ tolower/toupper char指针

mas*_*ask 0 c++ char-pointer toupper tolower

你们知道为什么下面的代码在运行时崩溃了吗?

char* word;
word = new char[20];
word = "HeLlo"; 
for (auto it = word; it != NULL; it++){        
    *it = (char) tolower(*it);
Run Code Online (Sandbox Code Playgroud)

我正在尝试小写char*(字符串).我正在使用visual studio.

谢谢

Eva*_*ran 6

你不能比较itNULL.相反,你应该比较*it'\0'.或者更好,使用std::string并且从不担心它:-)

总之,当循环C风格的字符串时.你应该循环,直到你看到的角色'\0'.迭代器本身永远不会NULL,因为它只是在字符串中指向一个位置.迭代器具有可与之比较的类型的事实NULL是您不应直接触摸的实现细节.

此外,您正在尝试写入字符串文字.这是禁止的:-).

编辑:正如@Cheers和hth所说.- tolower如果给出负值,Alf 可能会中断.很遗憾,我们需要添加一个强制转换,以确保在您提供Latin-1编码数据或类似数据时不会破坏.

这应该工作:

char word[] = "HeLlo";
for (auto it = word; *it != '\0'; ++it) {
    *it = tolower(static_cast<unsigned char>(*it));
}
Run Code Online (Sandbox Code Playgroud)