The code you have shown will not work as-is, as it has a lot of mistakes and undefined behavior in it.
using std::cout
without #include <iostream>
using <stdio.h>
instead of <cstdio>
in change()
, pointing s
to read-only memory (illegal in C++11 and later!), looping using an invalid loop counter, and trying to copy more characters from str
to s
than are allocated to s
.
in main()
, pointing str
to read-only memory.
You need to use something more like this instead:
#include <iostream>
#include <cstring>
using namespace std;
char* change(char *str)
{
int len = strlen(str);
char *s = new char[len + 1];
for(int i = 0; i < len; ++i)
{
s[i] = str[i] + 32;
}
s[len] = '\0';
return s;
}
int main()
{
char *str = change("SampleRun");
cout << str;
delete[] str;
return 0;
}
Or this:
#include <iostream>
#include <cstring>
using namespace std;
char* change(char *str, int len)
{
for(int i = 0; i < len; ++i)
{
str[i] += 32;
}
return str;
}
int main()
{
char str[] = "SampleRun";
cout << change(str, strlen(str));
return 0;
}
But, since you are using C++, you really should be using std::string
instead:
#include <iostream>
#include <string>
using namespace std;
string change(const string &str)
{
string s;
s.reserve(str.length());
for(char ch : str)
{
s.push_back(ch + 32);
}
return s;
}
int main()
{
cout << change("SampleRun");
return 0;
}
Or this:
#include <iostream>
#include <string>
using namespace std;
void change(string &str)
{
for(char &ch : str)
{
ch += 32;
}
}
int main()
{
string str = "SampleRun";
change(str);
cout << str;
return 0;
}
That being said, if your goal is to lowercase a string (the only sensible reason to add 32 to characters, unless you are trying to implement obscurity via a basic rotation cipher), then rather than blindly adding 32 to every character, consider using std::tolower()
instead. You can use that with std::transform()
, for instance. This is a common (albeit not an entirely accurate) way to lowercase strings in C++, eg:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
char* change(char *str)
{
int len = strlen(str);
char *s = new char[len + 1];
transform(str, str+len, s, [](unsigned char ch){ return tolower(ch); });
s[len] = '\0';
return s;
}
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
char* change(char *str, int len)
{
transform(str, str+len, str, [](unsigned char ch){ return tolower(ch); });
}
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
using namespace std;
string change(const string &str)
{
string s;
s.reserve(str.length());
transform(str.begin(), str.end(), back_inserter(s), [](unsigned char ch){ return tolower(ch); });
return s;
}
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
void change(string &str)
{
transform(str.begin(), str.end(), str.begin(), [](unsigned char ch){ return tolower(ch); });
}