Kralc's blog

By Kralc, history, 9 years ago, In English

When I was trying 5B, I get runtime error at the first time. I was frustrated since it works well in my computer. After observing the output from the judge, I suspected that there may be problem somewhere around the input handling part. So I re-wrote that part.

Original:

    int max = 0, i = 0, n;
    string in[1000];
    while(getline(cin, in[i])){
        if(in[i].size()>max)max = in[i].size();
        i++;
    }

Second version:

    int max = 0, i = 0, n;
    string in[1000];
    string tmp;
    while(getline(cin, tmp)){
        if(tmp.size()>max)max = tmp.size();
        in[i] = tmp;
        i++;
    }

It is accepted and I have no idea why....

  • Vote: I like it
  • +6
  • Vote: I do not like it

»
9 years ago, # |
  Vote: I like it +11 Vote: I do not like it

In the first version, assume there is 1000 lines in the input, the next iteration in the loop, the variable i will equal 1000. Although there is no line in the input and the loop would break, your code would access the 1000 (zero-index) element in the array, which is beyond its size.

  • »
    »
    9 years ago, # ^ |
      Vote: I like it +6 Vote: I do not like it

    Oh, I get it! Thanks khaledkee!