【问题标题】:Reversing a string in C++ using pointers使用指针在 C++ 中反转字符串
【发布时间】:2019-01-10 22:07:11
【问题描述】:
void reverse(char[] x) {
    char* pStart = x;
    char* pEnd = pStart + sizeof(x) - 2;
    while(pStart < pEnd) {
        char temp = *pStart;
        *pStart = *pEnd;
        *pEnd = temp;
        pStart++;
        pEnd--;
    }
}

int main() {
    char text[] = ['h','e','l','l','o'];
    reverse(text);
    cout << text << endl;
    return 0;
}

我是 C++ 和堆栈溢出的新手。

我正在尝试使用指针反转字符串...我不太明白我做错了什么。请帮帮我。

补充问题:字符串和字符数组有什么区别?

【问题讨论】:

  • 字符串是一个对象,正是你应该在这里使用的。
  • "字符串和字符数组有什么区别?" 假设你说的是std::string,这就像问袖珍计算器之间的区别和图形计算器。如果你可以在纸上多写一点来做额外的工作,他们都会给你相同的数字,但如果你给我一个,我知道如果我的口袋足够大,我会拿哪个。
  • 为什么不使用std::string s{"hello"}; std::reverse(s.begin(), s.end());
  • 警告:当使用像reverse 这样的通用标识符时,如果您选择使用using namespace std;,请格外小心在标准库中已经有一个std::reverse,您会发现自己收到了一些真正奇怪的东西如果代码与它发生冲突,则会出现错误消息或行为。
  • @user4581301 应该不是问题,因为没有人会做using namespace std,对吧?

标签: c++ string pointers reverse


【解决方案1】:

sizeof(x)x 是函数的 char[] 类型的参数不会给出字符串中的字符数,而是 char* 的大小,在 64 位系统上可能是 8 .您需要传递一个 C 字符串并改用 strlen(x)。将char text[] = {'h','e','l','l','o','\0'}char text[] = "hello" 写入main

请注意,sizeof() 需要在编译时进行评估;这在大小不确定的数组上是不可能的,比如char[]-typed 函数参数。但是,当在像 char text[] = {'h','e','l','l','o'} 这样的变量上使用 sizeof 时,sizeof(text) 将导致数组的实际大小。

【讨论】:

    【解决方案2】:

    char x[]char* x 相同,因此sizeof(x) 是指针的大小。因此,因为您无法计算声明它的块之外的数组的大小,所以我会从您的函数中删除该部分。

    为函数提供指向要替换的第一个和最后一个字符的指针会容易得多:

    void reverse(char* pStart, char* pEnd)
    {
        while (pStart < pEnd)
        {
            char temp = *pStart;
            *pStart   = *pEnd;
            *pEnd     = temp;
            pStart++;
            pEnd--;
        }
    }
    

    所以现在调用这个函数很容易 - 获取数组中相关字符的地址(使用 & 符号 &amp;):&amp;text[0]&amp;text[4]

    要显示一个字符数组,有一个规则,这样的“字符串”必须在最后一个字符之后有一个 NULL 字符。 NULL 字符可以写为0'\0'。这就是为什么它必须在这里添加到数组中。

    int main()
    {
        // char text[] = "hello"; // Same like below, also adds 0 at end BUT !!!in read-only memory!!
        char text[] = { 'h', 'e', 'l', 'l', 'o', '\0' };
        reverse(&text[0], &text[4]);
    
        std::cout << text << std::endl;
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-15
      • 2012-05-05
      • 2020-02-20
      • 1970-01-01
      • 1970-01-01
      • 2015-10-19
      相关资源
      最近更新 更多