Reputation: 3
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;
}
Upvotes: 0
Views: 225
Reputation: 1
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.
Upvotes: 0
Reputation: 10254
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.
Upvotes: 0
Reputation: 17668
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*’
Upvotes: 1