This may sound a bit stupid but this is how I am getting it and I have googled it but no relevant solution was found.
I always thought that in C, strings was terminated by '\0'
is a single character. (hence we used single quotes)
Also, we are able to do something like,
while ( a[i]!='\0' )
do blah blah
which suggests that '\0'
is a single character and ideally should be stored in a single position.
But when I declare an array like this:
char a[3];
and when I try to put some value say “hi” in it.
Then
printing a[0] gives "h"
printing a[1] gives empty space
printing a[2] gives 0
which is suggestive that \ was stored at position 1 and ‘0’ at position 2. and the whole thing ‘\0’ was not stored together despite us using it as a single character.
Why is it so? Can anyone shed some clarity on the same?
Thanks!
EDIT:
#include <stdio.h>
void main()
{
int i=0;
char a[2];
fgets(a,sizeof(a),stdin); // Here I input "Hi".
while(a[i]!='\0')
{
printf("%c",a[i]);
fflush(stdin);
i=i+1;
}
}
fgetstakes the size of the buffer as the second argument and reads that minus one characters, then makes the last character a\0. Because your array is sized 2 (which is too small for the stringhi, by the way),fgetsreads one character and makes the last character a\0, so you have an array that holdsh\0.To get it working, make your array sized 3; one for the
h, one for thei, and one for the\0: