Reversing string in C++

235 views Asked by At

In the following part of the string swap code

 end = &str[len - 1];

I am not understanding the addressing part. When I do it without the addressing part it still runs but gives me a warning that "a values of type char cannot be assigned to identity of type char". Here is the full code:

    #include<iostream>
    #include<cstring>
    using namespace std;

int main()
{
    char str[] = "This is a test";
    char *start, *end; 
    int len;
    int t; 

    cout << "Original " << str << "\n";
    len = strlen(str);
    start = str;
    end = str[len - 1];  

//this reverses the string
    while (start < end) { 

        t = *start;  
        *start = *end; 
        *end = t; 

        start++; 
        end--; 

    }
    cout << "Reversed" << str << "\n";
    system("PAUSE");
    return 0;
}
3

There are 3 answers

2
artm On BEST ANSWER

I am not understanding the addressing part.

Given

char str[] = "This is a test";
char *start, *end; 
len = strlen(str);

then end is pointer to char, and

end = &str[len - 1]; // `end` points to the last character (before the `\0`)

You must use the & (address of) operator because end is pointer and so it must be assigned to the address of something (here the address of the last character of the string).

When I do it without the addressing part it still runs

I don't think it will - you should have got a compile error

end = str[len - 1]; // invalid conversion from ‘char’ to ‘char*’
6
BlackMamba On

You should konw the type of end is char*, but the type of str[len-1] is char, so you need change type str[n-1] to char*, so you need &str[len-1].

But if you use string, there will be an easy method:

Use the std::reverse method from STL:

std::reverse(str.begin(), str.end()); //str shoud be string type

You will have to include the "algorithm" library, #include.

0
Sherwin V On

Maybe this can help

void reverse (char word[])
{
   int left = 0;
   int right = strlen(word) - 1;

   while (left < right)
   {
      char temp = word[left];
      word[left] = word[right];
      word[right] = temp;
      left++;
      right--;
   }
   cout << word;

}

I hope this gives you the idea.