-1

I have this part in the program

    char size_input[5]={'1','0','4','-'};
    for (int i=0;i<6;i++){
    cin >> size_input[i];
    if(size_input[i]!=char(45)){
        valid_size_characters++;
    }else{
        i=6;
    }
}

It compiles with no error in both windows and linux but in windows when the program reaches that part it just crashes and I have no idea why

  • The right tool to solve such problems is your debugger. You should step through your code line-by-line *before* asking on Stack Overflow. For more help, please read [How to debug small programs (by Eric Lippert)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). At a minimum, you should \[edit] your question to include a [Minimal, Complete, and Verifiable](http://stackoverflow.com/help/mcve) example that reproduces your problem, along with the observations you made in the debugger. – πάντα ῥεῖ Sep 10 '16 at 12:10
  • 1
    Change `i<6` to `i<5` in the for loop condition. – πάντα ῥεῖ Sep 10 '16 at 12:10
  • You're not comparing a char to an array, like you say in the title. You're comparing two chars. – chris Sep 10 '16 at 12:13
  • 1
    If you by `char(45)` mean the ASCII encoding for `'-'` then use the character instead of a [*magic number*](https://en.wikipedia.org/wiki/Magic_number_(programming)). – Some programmer dude Sep 10 '16 at 12:14
  • 1
    As for your problem, think a little. What is the valid range of indexes for an array of five elements? – Some programmer dude Sep 10 '16 at 12:15

1 Answers1

2

It's an off-by-one error because your array has a size of 5 while the loop runs 6 times resulting in writing out of the array bounds causing undefined behavior. So it should be i<5 instead of i<6.

Also avoid exiting the loop by manipulating the loop index i, instead you could use break.

BnBDim
  • 136
  • 5