2-D char array gives wrong while array of string gives correct answer

[Solved]
Question
Submission 1
Submission 2
Both the submissions are exactly same except in the first submission i am using

string grid[n]; (right answer)

and in second submission i am using

char grid[n][m]; (wrong answer)

Can anyone please tell me the reason for this behaviour in C++
@vijju123

Thanks in advance…!

Very puzzling. The only situations that I can think of where this would make a difference is when the input is misformatted (not uncommon with External Contests), but in that case I’d expect that the char array version would give the correct answer - unless the expected output was wrong, too XD

Edit: Unless one of the lines contained a string that was longer than m - that would favour the string solution over the char one, I think.

1 Like

Let’s rule out some possibilities. Can you submit the following and post a link to the submission? It will either give WA or RE.

#include <iostream>
#include <cassert>

using namespace std;

int main()
{
    int n, m;
    cin >> n >> m;
    for (int i = 0; i < n; i++)
    {
        string line;
        cin >> line;
        assert(line.size() == m);
    }
    assert(cin);
}
2 Likes

https://www.codechef.com/viewsolution/37508558
It gives runtime error.

1 Like

Thanks! Let’s narrow it down further. If my “Edit” in the post above is on the mark, this will also be a RE; please submit and post the link :slight_smile:

#include <iostream>
#include <cassert>

using namespace std;

int main()
{
    int n, m;
    cin >> n >> m;
    for (int i = 0; i < n; i++)
    {
        string line;
        cin >> line;
        assert(line.size() <= m);
    }
}

1 Like

https://www.codechef.com/viewsolution/37508666
Yes, RE

1 Like

Aha - so at least one line in the test input is longer than it’s supposed to be, and this will favour the string solution.

For example, let’s take the sample test input:

3 3
abc
elm
xet

Imagine if we accidentally added a character to one of the strings:

3 3
abc
elmz
xet

The version using string would give the same answer as for the “correct” version of this test input, whereas the version using char arrays would give the wrong answer.

3 Likes

Thanks a lot, Apparently this cost me 2 hours of debugging my solution.
But thanks for helping me out.!

1 Like

But in the solution in both cases i am accessing m characters of the string, so should’nt it be same thing or the expected output is also wrong bcoz of this?

Try it and see :slight_smile:

2 Likes

Yups, expected output also becomes wrong…!