Sachin Narendran Sachin Narendran - 2 months ago 8
C Question

Junk values while reversing a string?

My program is to reverse, even though the reverse is being generated but the problem is there is an unwanted junk values too.

I am not able to understand where the problem is.

#include <stdio.h>
#include<string.h>
int main()
{
char ar[100],b[100];
int i,j;
scanf("%s",ar);
j=strlen(ar);
printf("%d",j);
j-=1;
for(i=0;j>=0;i++)
{
b[i]=ar[j];
j--;
}
printf("\n %s",b);
}


This is the output:
enter image description here

Answer

You need to add

b[i] = 0;

at the end to terminate the string.