So here I'm trying to enter a string and reverse it manually in C. If I just use a number let's say 5 as the length of the string directly everywhere (while creating the character array, in for loops) then the code works fine.
But if I take a variable to store the length and take user input for the length, let's say we enter 5, then I get an output like this
enter length : 5
enter string of length 5 : apple
the string is :
appl
rev string is : lppa
Why am I missing the last character
If I just assign value to the variable during declaration i.e. int len = 5;
then the code works fine too
The issue is only when I take user input for len variable
Here is my code
include <stdio.h>
int main()
{
int len;
printf("enter length : ");
scanf("%d", &len);
int i, j = len-1;
char str[len], rev[len];
printf("enter string of length %d : ", len);
for (i = 0; i < len; i++)
{
scanf("%c", &str[i]);
rev[j] = str[i];
j--;
}
i = 0;
printf("the string is : ");
for (i = 0; i < len; i++)
printf("%c", str[i]);
j = 0;
printf("\nrev string is : ");
for (j = 0; j < len; j++)
printf("%c", rev[j]);
return 0;
}