URI 2399 5% C++ error

Asked

Viewed 144 times

0

Guys, my code is giving 5% error and I can’t find a why, it’s the question of the minefield:

#include <iostream>

using namespace std;

int main(){
    int N, i;
    int qtbombas;
    cin >> N;    

    int tabuleiro[N];

    for(i = 0; i < N; i++){
    cin>>tabuleiro[i];
    }//inserir bombas no tabuleiro 
    for(i = 0; i < N; i++){/*calcular e printar a quantidade de bombas nos arredores*/
        if (i == 0)
            qtbombas = tabuleiro[i]+tabuleiro[i+1]; 

        else if (i == N-1)
            qtbombas = tabuleiro[i]+tabuleiro[i-1];   

        else
            qtbombas = tabuleiro[i]+tabuleiro[i-1]+tabuleiro[i+1];

        cout<<qtbombas<<endl;
    }

    return 0;
}

Link to the question: https://www.urionlinejudge.com.br/judge/pt/problems/view/2399

  • 2

    What should the code do? What is it doing? What are the tested inputs? What were the outputs produced? What were the expected outputs?

  • @Andersoncarloswoss The statement, example of entries and the rest is on the link: https://www.urionlinejudge.com.br/judge/pt/problems/view/2399

  • Your code seems correct, although it could have been better. I can’t see where the error is. URI gave you some error message or reason why something went wrong?

1 answer

1

Runtime-defined arrays, also known as VLA’s (English variable length array) are not allowed by ISO C++ Standard, so the problem is in this line of code int tabuleiro[N];.

For you to fix, you can use a std::vector, or alternatively replace the indicated row by int* tabuleiro = new int[N]; and, at the end of the programme, before return 0;, insert delete[] tabuleiro;.

Finally, one detail: C99 allows this type of array and the GCC compiler, by extension, accepts them in C90 and C++, so you may come across programs containing VLA’s in C++, although this is not predicted by C++ Standard and is completely dependent on the implementation.

If you are interested in more details about VLA’s, check out: Arrays of Variable Length and Why aren’t variable-length arrays part of the C++ standard? .

Browser other questions tagged

You are not signed in. Login or sign up in order to post.