Reversing a string (URGENT HELP!!)

I made a program to reverse a string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream.h>
#include <conio.h>
#include <string.h>

void main()
{
char srcstr[30],desstr[30];
int i,len;
clrscr();
cout<<"\nenter the string\n";
cin>>srcstr;
len=strlen(srcstr);
for(i=0;srcstr[i]!='\0';i++)
{
desstr[--len]=srcstr[i];
}
desstr[i]=0;
cout<<desstr;
getch();
}


When I executed it..the string was reversed but some special characters were appearing in front of the reversed string..so my teacher asked me to add
desstr[i]=0; to the program. Please let me know..y there was a need to add "desstr[i]=0;"??
Because all strings must be terminated with a null character ('\0', or just 0).
That's how cout (and many other functions that work with C strings) knows where the end of the string is.
Otherwise, it keeps going past the end of the string until it happens to run into a null character somewhere in memory that you're not supposed to be accessing.
ohhh..so..the new string..I created i.e desstr din't finish at a null character...! Thank u !!
Topic archived. No new replies allowed.