c++ - 在 C++ 中反转字符串

标签 c++ string pointers reversing

在下面的字符串交换代码部分

 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/

相关文章:

检查字符串 A 是否出现在字符串 B 的末尾

xcode - 本地化不适用于 XCode 6 中的 XIB 文件

c++ - 使用指针遍历多数组

c++ - 数组结束时指针不应该指向 nullptr 吗?

c++ - 枚举器运算符重载 C++ 中的 '&' token 之前的预期初始值设定项

c++ - 跨数据 block 的连续流计算

c++ - 如何将字符转换为整数

c++ - 我的程序使用了无效的编译器,如何找到正确的编译器?

string - VBA 如果单元格中的前 6 个字符不等于 01/01/then

你能从 C 中的 void * 打印值吗