c++ - 动态长度的字符数组

标签 c++ pointers nullpointerexception char

我写了一个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;
}

我猜想存在某种内存访问冲突。

知道为什么这不起作用吗?

错误:段错误(核心转储)

最佳答案

通过 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/

相关文章:

C指针的烦恼

java - Google Maps API v2 调用 getmap() 抛出 NullPointerException

java - 什么是 NullPointerException,我该如何解决?

c++ -/usr/bin/ld : cannot find -lpthreads

c++ - 成员(member)功能和非成员(member)功能如何选择?

c++ - 将 native 指针转换为托管对象

c++ - 如何在不重建数组的情况下将 vector<vector<int>> 转换为 int**?

C++/Arduino 将函数作为参数传递

c - 错误 "invalid use of undefined type ' struct cmplx'取消引用指向不完整类型的指针”。如何修复它?

java - 链表迭代异常