Search code examples
c++touppertolowerchar-pointer

C++ tolower/toupper char pointer


Do you guys know why the following code crash during the runtime?

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

I'm trying to lowercase a char* (string). I'm using visual studio.

Thanks


Solution

  • You cannot compare it to NULL. Instead you should be comparing *it to '\0'. Or better yet, use std::string and never worry about it :-)

    In summary, when looping over a C-style string. You should be looping until the character you see is a '\0'. The iterator itself will never be NULL, since it is simply pointing a place in the string. The fact that the iterator has a type which can be compared to NULL is an implementation detail that you shouldn't touch directly.

    Additionally, you are trying to write to a string literal. Which is a no-no :-).

    EDIT: As noted by @Cheers and hth. - Alf, tolower can break if given negative values. So sadly, we need to add a cast to make sure this won't break if you feed it Latin-1 encoded data or similar.

    This should work:

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