Adhami's blog

By Adhami, history, 7 years ago, In English

I was solving 408B and it was easy. I submitted the code and I get WA in test 15. Then I have revised the code and changed the arrays' size from 1000 to 1005 and it worked! In the problem maximum length of both strings is 1000. why did that happen? first submission WA on test 15 : 28983405. second submission Accepted : 28983523

please do not down vote before telling me what is the wrong in my question

UPD: Thanks to fresher96 for his explanation

UPD:scanf format string article in Wikipedia mentions that:

%s : Scan a character string. The scan terminates at whitespace. A null character is stored at the end of the string, which means that the buffer supplied must be at least one character longer than the specified input length.

  • Vote: I like it
  • -3
  • Vote: I do not like it

»
7 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by Adhami (previous revision, new revision, compare).

»
7 years ago, # |
  Vote: I like it +14 Vote: I do not like it

the size should be at least 1001, see
http://mirror.codeforces.com/contest/408/submission/28984351.

you have 1000 characters + the null character in the end.
for example if you read the string "abc" in the varibale char s[100] it will be stored like this:
s[0] = 'a', s[1] = 'b', s[2] = 'c', s[3] = '\0', s[4], s[5], ... = something random.

  • »
    »
    7 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Thanks so much.

    But if we had int a[100] will the same thing happen?

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

      no. even if you have char a[100] you can read 100 characters. like this for example

      for(int i=0; i<100; i++)
          cin>>a[i];
      

      because here you deal with a[] as an array of chars.
      while by using scanf("%s") means that you are dealing with a[] as a null-terminated string. the same thing happens when using printf or gets or C-builtin methods like strcmp.

»
7 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Why so miser ?? Declear array at least 5 size more than you need.

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

    To become a good programmer you should understand what you code. :)

    • »
      »
      »
      7 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      That's right. But to do good in contest you should not take any risk.

      • »
        »
        »
        »
        7 years ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        As a programmers we learn from trying. And for me I will not get WA because of array size again.