Here is my code
#include<iostream>
#include<string>
using namespace std;
char* getString(char*& s)
{
string str;
getline(cin, str);
int length = str.length();
s = (char*)malloc(length);
for (int i = 0; i < length; ++i)
s[i] = str[i];
return s;
}
void main()
{
char* s;
getString(s);
cout << s << endl;
}
In my getString()
function, I create a string str
and pass the input string to it. Then I calculate for the length of str
and then allocate this number of bytes for the char array s
. But the problem is, when i call for strlen(s)
, the return value is not equal to the length of string str
, so when i print out s
to the console, it's not the string i want. Anyone can tell me why and explain more about it??