-3

How can I check that a char array is null terminated?

char input[80];

fgets(input, sizeof(input), stdin);

for (i = 0; input[i]; i++)
{
    if (input[i] == '\0') {
       printf("null!!!"); // never works
    }
}

For example, the below code does not print null.

avasin
  • 9,186
  • 18
  • 80
  • 127

4 Answers4

7

In your for loop condition, you're already checking for the non-0 value of input[i], so the inside if is a dead condition.

To test, make an infinite loop, check if and then, print and break out. Something like

for (i = 0; ; i++)
{
    if (input[i] == '\0') {
       printf("null!!!\n");  // now works
       break;
    }
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
2

As soon as input[i] is 0 the loop exits, so that print statement is never executed.

John Bode
  • 119,563
  • 19
  • 122
  • 198
1

Here is another working code, if you are interested :

#include <stdio.h>
#include <stdlib.h>

int main() {
    char input[] = "I am a string !!";
    int i = 0;
    while(1) {
        if (input[i] == '\0') {
           printf("null!!!");
           break;
        }
        i++;
    }
}
Magix
  • 4,989
  • 7
  • 26
  • 50
0

All answers here don't check memory bounds, so you'll definitely run into a segmentation fault. Still, if an error occurs during freading, you may have garbage in input.

char input[80];

fgets(input, sizeof(input), stdin);

for (i = 0; i<80; i++)
{
    if (input[i] == '\0') {
        printf("null!!!"); 
    }
}

You could also change if (input[i] == '\0') to just if (! input[i]) since '\0' (null-terminator) has ASCII value 0.

ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • 1
    With all due respect, did you read the `fgets()` man page before nominating other answers as faulty? Isn't it indirectly impose the bounds ? :) – Sourav Ghosh Jan 27 '16 at 16:02
  • @SouravGhosh, yes, why? OK, I now see these answers have a `break` after printing. – ForceBru Jan 27 '16 at 16:07
  • `if ( ! input[i])`will be executed also for `0` value, isn't it? (valid char) – avasin Jan 27 '16 at 16:11
  • 1
    @avasin, `! input[i]` will evaluate to true only if `input[i]` is zero and a null-terminator is `0` in ASCII. – ForceBru Jan 27 '16 at 16:12