反转字符串 [英] reversing of a string

查看:148
本文介绍了反转字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<iostream>
#include<string.h>
using namespace std;
char * reverse (char *);
int main()
{
    char * a;
    cout<<"enter string"<<endl;
    gets(a);
    cout<<a;
    cout<<"the reverse of string is"<<reverse(a);
    return 0;
}
char * reverse (char * b)
{
    int i,j=strlen(b);
    for(i=0;b[i]!='\0';i++)
    {
        char temp;
        temp=b[j-i-1];
        b[j-i-1]=b[i];
        b[i]=temp;
    }
    return b;
}

这个程序没有给出编译时错误。并且不提供期望的输出。请解释原因。因为我在C ++中没有那么好,所以如果我的问题不能达到标准,请原谅我。

This program is giving no compile time error.But it does give run time error and does not give desired output. Please explain the cause.As I am not that much good in C++ so please forgive me if my question is not upto mark.

推荐答案

您不是为字符串分配内存。 get 不会为您分配内存,因此您只是读入一些随机位置 - 结果未定义。

You are not allocating memory for the string. gets doesn't allocate memory for you, so you're just reading into some random location - results are undefined.

除此之外,还有更多的问题:

Apart from that, there are more problems:


  • 这是标记的C ++,但它更像C和cout c> string 将是一个更好的主意)

  • 您正在使用 gets c> fgets 。 get 是相当危险的,应该避免。

  • This is tagged C++ but it's more like C with cout (using string would be a better idea)
  • You are using gets instead of fgets. gets is quite dangerous and should be avoided.

这篇关于反转字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆