当我尝试反转字符*时出现意外输出

Unexpected output when I try to reverse a char*

本文关键字:意外 输出 字符      更新时间:2023-10-16
#include<iostream>
#include<string>
using namespace std;
void reverse(char* str)
{
    char *new_str = str;
    while(*new_str != 'n'){
        new_str++;
    }
    while(new_str != str){
        cout << *new_str;
        new_str--;
    }
    cout << *new_str;
}
int main()
{
    char *str = new char[1024];
    str = "hello world";
    reverse(str);
}

当我尝试运行它时,我得到一些疯狂的输出,我的电脑开始发出哔哔声。我在这里公然做错了什么?

C 字符串的末尾由字符 '' 标记。您使用了换行符'n'

你的意思是除了使用裸漏new之外,弃用的char*而不是const char*甚至更好的std::string,不使用标准库算法std::reverse,将IO与您的算法混合并包括整个namespace std(这可能会间接std::reverse()范围),而不将您自己的reverse()放在自己的命名空间中?

#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
// using namespace std; // for the brave, and drop the std:: in the next 3 lines
int main()
{
    std::string str = "hello world";    // std::string instead of char*
    std::reverse(begin(str), end(str)); // standard library algorithm
    std::cout << str;                   // IO separate from algorithm
}

如果您只对如何编写反向算法感兴趣,这里有一种方法可以做到这一点,而无需依赖您有一个空终止符的事实:

template<class BidirIt>
void reverse(BidirIt first, BidirIt last)
{
    while ((first != last) && (first != --last)) {
        std::swap(*first++, *last);
    }
}

问题是,首先你为 str 分配了分配内存的地址,然后将其重新分配给指向 C++ 中类型为 const char[] 的字符串文字。

char *str = new char[1024];
str = "hello world";

此字符串文本的结尾为零字符"\0"。它没有换行符 ''。因此,该函数无效,因为它将尝试访问搜索新行字符的数组之外的内存。

有效代码可能如下所示

#include <iostream>
using namespace std;
void reverse( const char* s )
{
    const char *p = s;
    while ( *p ) p++;
    while ( p != s ) cout << *--p;
}
int main()
{
    const char *s = "hello world";
    reverse( s );
}

或者,如果您想自己以交互方式输入字符串,则 main 可能看起来像

int main()
{
    const size_t N = 1024;
    char s[N];
    cout << "Enter a statement: ";
    cin.getline( s, N );
    reverse( s );
}

更正您的函数:

void reverse(char* str)
{
    char *new_str = str;   
    while(*new_str){ // use this instead of *new_ptr != 'n'
        new_str++;
    }
    while(new_str != str){
        cout << *new_str;
        new_str--;
    }
    cout << *new_str;
}