Search code examples
cnullchar

Printing char array with null character in the middle in C


I have noticed that when you try to print a null character in C, nothing will get printed.

printf("trying to print null\n");
printf("%c", '\0');

However, I am trying to print the characters in the following array one by one, up to the sixth character which is the null character.

char s[] = "Hello\0Bye";
int i;
for(i = 0; i < 7; i++) {
    printf("%c", s[i]);
}
printf("\n");

I was expecting "Hello" to be printed, as since the sixth character is null nothing will be printed. However my output was: "HelloB". It seems like printf skipped the null character and just went to the next character. I am not sure why the output is "HelloB" instead of "Hello".

Any insights would be really appreciated.


Solution

  • The construction '\0' is commonly used to represent the null character. Here

    printf("%c", '\0');
    

    it prints nothing.

    And in the decalaration of s

    char s[] = "Hello\0Bye"; 
    

    when you print like

    for(i = 0; i < 7; i++) {
        printf("%c", s[i]); 
    }
    

    printf() prints upto 0<7(h), 1<7(e)..5<7(nothing on console),6<7(B) iterations only and 6th charactar is B hence its prints HelloB.

    I was expecting "Hello" to be printed ? For that you should rotate loop until \0 encountered. For e.g

    for(i = 0; s[i] != '\0'; i++) { /* rotate upto \0 not 7 or random no of times */ 
       printf("%c", s[i]); 
    }
    

    Or even you no need to check s[i] != '\0'

    for(i = 0; s[i]; i++) { /* loop terminates automatically when \0 encounters */ 
         printf("%c", s[i]); 
    }