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

8
  • 1
    This is C++ code, not C code, and should be tagged with the C++ tag, not the C tag. Commented Aug 6, 2020 at 2:31
  • No it's not @d4rk4ng31 Commented Aug 6, 2020 at 2:36
  • Oh okay, its a reference!! Sorry Commented Aug 6, 2020 at 2:38
  • 1
    this is c++ use new instead of malloc() Commented Aug 6, 2020 at 2:54
  • 1
    If you have to do things a specific way because of an assignment specification, you should explain this up front. Commented Aug 6, 2020 at 3:11

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Also, if this answer worked for you, please accept it
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.