Here I'm using two string
char str[5], rev[5];
Initially I was trying to performe reverse of a string and it was successful.
While I'm printing the characters of rev
string I mistakenly exceed the limit of string, but still string rev
printing the characters of it.
First I accessed 6 elements from string, in that last element was
blank . This is OKAY because last character having '\0'.
But when I try to access more than 6 elements it's printing the character which are belong to given string ( in my case it is rev
) and some are characters.
This is my code
#include <stdio.h>
int main()
{
char str[5] = "Hello";
char rev[5];
int i = -1, j = 0;
while(str[++i] != '\0');
while(i >= 0)
{
rev[j++] = str[--i];
}
printf("\n i = %d ", i);
printf("\n j = %d \n\n ", j);
rev[--j] = '\0';
printf("%s is reversed string \n ", rev);
for(int k = -5; k <= 15; k++)
{
printf("\n k --> %d = %2c", k, rev[k]);
}
return 0;
}
I don't understand how this working
$ ./a
i = -1
j = 6
olleH is reversed string
k --> -5 = �
k --> -4 = �
k --> -3 = �
k --> -2 =
k --> -1 =
k --> 0 = o <- Here is the starting point
k --> 1 = l
k --> 2 = l
k --> 3 = e
k --> 4 = H
k --> 5 =
k --> 6 = e <--|
k --> 7 = l <--| From where it comes
k --> 8 = l <--| And how
k --> 9 = o <--|
k --> 10 =
k --> 11 =
k --> 12 =
k --> 13 =
k --> 14 = H <--| This one as well
k --> 15 = �
May be this questios sounds weird**.**