当我尝试反转字符*时出现意外输出
Unexpected output when I try to reverse a char*
#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;
}
相关文章:
- 字符串比较中的意外输出
- 来自 decltype 的意外输出类型
- 字符数组到十六进制字符串的转换 - 意外输出
- 使用 boost::regex 从目录中获取带有一些正则表达式的文件名称时出现意外输出
- 使用后序遍历递归的深度优先搜索会产生意外输出
- C++的意外输出
- 贝金纳C++练习解决方案的意外输出
- 无效* 转换获得意外输出
- 以下程序的意外输出
- 意外输出:矢量矢量(功率集)
- 基本 int 数组提供意外输出
- 线程的意外输出
- 减法中的意外输出
- 带有左移操作员C 的意外输出
- C strncpy意外输出
- 意外输出..函数绑定在虚拟表中的发生方式
- 星号的意外输出
- 已编译的 protobuf 文件的意外输出路径
- 打印对象矢量的意外输出
- 递归函数用于计算 n 个数字之和的意外输出