Rokni Rokni - 22 days ago 5
C++ Question

c++ How to change a character in char* in for loop

Hey guys i got an assignment that i cant seem to solve. I get a char* string and i need to make all upper case letters (everything is in ASCII) to lower case using bit operations. I'm adding my code but it keeps crashing.

#include <iostream>
#include <cstring>

using namespace std;

void convertToLower(char* string)
{
for (unsigned int i = 0; i < strlen(string); i++)
{
if (string[i] >= 65 && string[i] <= 90)
{
string[i] |= 32;
}
}
cout << string << endl;
}
int main()
{
convertToLower("Hello");
return 0;
}

Answer

You're trying to modify a string literal i.e. read-only memory: that's the reason for your crash (or undefined behavior to be more precise)

void convertToLower(char* str)
{
   for (unsigned int i = 0; i < strlen(str); i++)
   {
       if (str[i] >= 65 && str[i] <= 90)
       {
           str[i] |= 32;
       }
   }
   cout << str << endl;
}

int main() {

    char arr[] = "STRING";
    convertToLower(arr); // Fine

    char *readonly = "READONLY";
    convertToLower(readonly); // Nope
}

I suppose a recent compiler should also have warned you of this (Wwritable-strings).

Read more about this issue here: Why are string literals const?