1

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??

2 Answers2

2

You need to allocate one more character than str.length() to allow for the null character that terminates the string, and you need to set that character to the null character.

bitmask
  • 32,434
  • 14
  • 99
  • 159
Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
1

When you have an array of characters the very last byte is called the null terminator, which is \0 in this case. Its what tells your program where the end of the characters in an array are.

The str.length() function returns how many bytes are in a string. A null character does not count as a byte. So when str.length() goes to count how many characters are in your array, it counts until it reaches \0.

When you need to create a new array of the same 'size' as the string, you must make it one byte longer in order to accommodate the null terminator.

So your code should be:

s = (char*)malloc(length + 1);
Ovcheric
  • 149
  • 1
  • 9