There is no "string constant" in the code you have shown, so it would have to be at the call site, ie if you were doing something like invertirCase("string")
, which will not work, for 2 reasons:
since C++11 onward, C++ does not allow a string literal to be assigned to a char*
pointer. This is because a string literal is a const char[]
array, and you can't have a pointer-to-non-const pointing at const data. So you need to use const char*
instead.
however, that will still not work, because invertirCase()
modifies the data pointed at by its str
parameter. You can't modify the data of a string literal.
So, you will have to make a copy of the string literal into writable memory. You can either make that copy at the call site, eg:
char str[] = "string";
invertirCase(str);
Or, you can make the copy inside of invertirCase()
(but then the caller will have to free the copy when done using it), eg:
char* invertirCase(const char* str){
int size = 0;
char* retorno = new char[strlen(str)+1];
while (*str != '\0') {
retorno[size] = (*str < 96) ? (*str + 32) : (*str - 32);
str++;
size++;
}
retorno[size] = '\0';
return retorno;
}
char *str = invertirCase("string");
...
delete[] str;
Otherwise, simply don't use char*
at all. Use std::string
instead, eg:
std::string invertirCase(const std::string &str){
std::string retorno;
retorno.reserve(str.size());
for(char ch : str) {
retorno.push_back((ch < 96) ? (ch + 32) : (ch - 32));
}
return retorno;
}
std::string str = invertirCase("string");
...