c++ How to change a character in char* in for loop -
hey guys got assignment cant seem solve. char* string , need make upper case letters (everything in ascii) lower case using bit operations. i'm adding code keeps crashing.
#include <iostream> #include <cstring> using namespace std; void converttolower(char* string) { (unsigned int = 0; < strlen(string); i++) { if (string[i] >= 65 && string[i] <= 90) { string[i] |= 32; } } cout << string << endl; } int main() { converttolower("hello"); return 0; }
you're trying modify string literal i.e. read-only memory: that's reason crash (or undefined behavior more precise)
void converttolower(char* str) { (unsigned int = 0; < 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 recent compiler should have warned of (wwritable-strings
).
read more issue here: why string literals const?
Comments
Post a Comment