Hi all,
I jus wanna print string b after reversing it. but the out put is blank. My code snippet is below. :wall:
int main()
{
char * a, * b;
b = new char;
a = new char;
int len, le;
le = 0;
cout<< " enter your string \n";
cin>> a;
len = strlen(a);
for(int i = len-1; i>=0 ; i--)
{
le = len - i;
b[le]= a;
}
cout<< endl << b;
return 0;
}
It's a while ago for me, but it should be something like:
int main()
{
char * a, * b;
b = new char[64]; // allocate enough memory for the variables
a = new char[64];
int len, le;
le = 0;
cout<< " enter your string \n";
cin>> a;
len = strlen(a) - 1;
while(a[le]) {
b[le]=a[len];
le++;
len--;
}
b[le] = '\0'; // Terminate the string
cout<< endl << b;
return 0;
}
Note how it limits itself: Every time it calls itself again, it does so on a string one character shorter: reverse(str+1) ...and when it gets a string of zero length, it doesn't call itself at all: f ( '\0' == *str ) return;
So it wouldn't overflow the stack unless you had a string long enough to actually fill the stack with function calls.