0

I have a statement for displaying a char* string. but I do not see anything printed on screen when I try to cout a char* string. Below is my code:

char* reverseString(char *inputString)
{
    int i=0, length=0;
    char *reversedString = (char*)malloc(100);
    strcpy(reversedString,inputString);
    while(inputString[i]!='\0')
    {
        i+=1;
        length+=1;
    }

    for(int i=0;i<length;i++)
    {
        reversedString[i]= inputString[length-i];
    }
    cout<<endl<<"In Function, Reversed String: "<<*reversedString<<endl;
    return reversedString; 
}
int main()
{
    char string[100],*reversedString;
    cout<<"Enter string: ";
    scanf("%s",string);
    cout<<"\nString is: "<<string;
    reversedString = reverseString(string);
    cout<<endl<<"In Main, Reversed String: "<<*reversedString<<endl;
    return 0;
}
6
  • 7
    When I see someone just starting out using both cout and malloc, it really makes me wonder where you are getting these examples? Why mixing these parts of C and C++? cout and scanf() is even a bigger head-scratcher. Commented Nov 21, 2013 at 15:23
  • 2
    Did you try it without dereferencing reversedString? Commented Nov 21, 2013 at 15:23
  • Why use scanf instead of std::cin? Commented Nov 21, 2013 at 15:25
  • Oh, and unless this is for an exercise, you should probably use std::reverse. Commented Nov 21, 2013 at 15:29
  • @Chad: There seem to be some "C++ is just a better C" profs out there insisting on these chimeras... Commented Nov 21, 2013 at 15:30

2 Answers 2

5

It's because you reverse the whole string including the terminating '\0' character. So in the reversed string the very first character is the string terminator (and the last is the original strings first character, so if you skip "reversing" the terminator then the string is unterminated).

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

Comments

1

Start your for loop in reverse function with i = 1. And then add one more statement reversedString[i] = '\0' to append your string with \0.

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.