#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;
}
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.
You are not allocating memory for the string.
getsdoesn’t allocate memory for you, so you’re just reading into some random location – results are undefined.Apart from that, there are more problems:
stringwould be a better idea)getsinstead offgets.getsis quite dangerous and should be avoided.