edges of an array N x N

0

I would like to know how to set the edge values of an array to -1. I've tried to create an array of N + 2 x N + 2, and do it with a single, go through the edges, but when I put it to print it displays some strange values. I believe you have accessed the unavailable memory region.

Follow the code below:

void ConstroiTabuleiro(){
    // Aloca espaco na memoria para o tabuleiro
    tabuleiro = new int*[N+3];
    for(int i= 0; i <= N; i++){
        tabuleiro[i] = new int[N+3];
    }

    // Define as bordas como -1
    for(int i = 0; i <= N; i++){
       tabuleiro[0][i]  = -1;
       tabuleiro[i][0]  = -1;
       tabuleiro[i][N]  = -1;
       tabuleiro[N][i]  = -1;
    }

    // Inserindo NxN pecas aleatorias no tabuleiro
    for(int i= 1; i < N; i++){
        for(int j= 1; j < N; j++){
            tabuleiro[i][j] = rand()%D+1;
        }
    }

}

void ImprimeTabuleiro(){
    for(int i= 0; i <= N; i++){
        for(int j= 0; j <= N; j++){
            cout<<setw(3)<<tabuleiro[i][j];
        }
        cout<<endl;
    }
}

PS: In main() I only get the values of N , D and S which is the seed for the rand() function, these variables are global.

    
asked by anonymous 09.02.2018 / 04:17

1 answer

1
// Inserindo NxN pecas aleatorias no tabuleiro
for(int i= 0; i <= N; i++)
{
    for(int j= 0; j <= N; j++)
    {
        //  Se for a primeira linha OU coluna OU a ultima linha OU coluna
        //  adiciona -1
        if (i == 0 || j == 0 || i == N || j == N)
            tabuleiro[i][j] = -1;
        else
            tabuleiro[i][j] = rand()%D+1;
    }
}

Just add -1 in the first and last rows and columns.

Remember to add +2 to N.

    
09.02.2018 / 11:13