在下面的字符串交换代码部分
end = &str[len - 1];
我不理解寻址部分。当我在没有寻址部分的情况下执行此操作时,它仍然会运行,但会警告我“不能将 char 类型的值分配给 char 类型的标识”。这是完整的代码:
#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;
}
最佳答案
I am not understanding the addressing part.
给定
char str[] = "This is a test";
char *start, *end;
len = strlen(str);
然后 end
是指向 char 的指针,并且
end = &str[len - 1]; // `end` points to the last character (before the `\0`)
你必须使用&
(地址)运算符,因为end
是指针,所以它必须被分配给某物的地址(这里是最后一个字符的地址)字符串)。
When I do it without the addressing part it still runs
我不认为它会 - 你应该有一个编译错误
end = str[len - 1]; // invalid conversion from ‘char’ to ‘char*’
关于c++ - 在 C++ 中反转字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41539830/