0

Im using this double while loop. Im new to C.

int crawler; char *desired[100]; crawler = getchar(); while(crawler != EOF) { int i = 0; while((crawler != '\n') && (crawler != EOF)) { desired[i] = crawler; i++; crawler = getchar(); } printf("%s", desired); } 

I just dont see why Im getting infinite loop in here (LLLLLLLLL..). Stdin looks like this:

Lorem(newline) Ipsum(newline) Beach(newline) Crocodile(newline) Crox(newline) C(EOF) 

Any idea? thanks.

4
  • 6
    char *desired[100]; -> char desired[100];. Also turn on compiler warnings (gcc -Wall ...) and pay attention to them ! Commented Oct 18, 2017 at 10:59
  • thanks, i missed that. Commented Oct 18, 2017 at 11:00
  • 4
    1.) printf("%s", desired); <- you can't guarantee desired is a string here, it probably doesn't contain a terminating \0 byte! 2.) your inner loop will happily overflow desired, add a check! Commented Oct 18, 2017 at 11:01
  • 1
    And don't forget that char strings in C are really called null-terminated byte strings. That null-terminator Is important to not forget. Commented Oct 18, 2017 at 11:01

1 Answer 1

3

Your outer loop ends when crawler is EOF.

Your inner loop ends when crawler is '\n' or EOF.

Only the inner loop reads input (by calling getchar).

Therefore: As soon as the first '\n' is read, the inner loop is never re-entered (the condition rejects '\n'), but the outer loop doesn't end, and it never changes the value of crawler.

Result: The outer loop spins without reading any input.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.