我写了一个C++函数,可以表示如下: 它所做的只是获取一个字符串(这是它崩溃的地方)并将其反转。
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
int main()
{
cout<<"Enter a string: "<<endl;
char *str;
gets(str);
cout<<"Reversed String is: ";
for(int i=strlen(str)-1;i>=0;i--)
cout<<(str[i]);
return 0;
}
我猜想存在某种内存访问冲突。
知道为什么这不起作用吗?
错误:段错误(核心转储)
最佳答案
在 c++通过 algorithm
中的 std::reverse
可以更简单、更不易出错地解决此问题。而且它更容易使用 std::string
。
#include <iostream>
#include <algorithm>
int main ()
{
std::string input;
std::cout << "Enter string to reverse: ";
std::cin >> input;
std::reverse(input.begin(),input.end());
std::cout << "Reversed string: " << input << std::endl;
return 0;
}
如果您必须通过字符数组来完成此操作,请尝试此操作(您甚至不需要动态内存分配)
#include <iostream>
#include <algorithm>
#include <cstring>
int main ()
{
char input[1024];
puts("Enter string to reverse: ");
fgets(input, 1024, stdin);
std::reverse(input, input + strlen(input));
printf("Reversed string: %s", input);
return 0;
}
关于c++ - 动态长度的字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45902976/