edges of an N x N matrix

Asked

Viewed 800 times

0

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

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 the main() I receive only the values of N, D and S which is the Seed for function rand(), these variables are global.

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.

  • i and j will never be 0 or N.

  • @Márioferoldi Thanks. I copied his for without modifying.

  • Hi @Liquidpenguin, thanks for replying. I tested your code here, and when you printed the board the edges were right, but only N-1 rows and columns were filled with random numbers. What I intend to do is leave the N rows and columns normal numbers, and the N+1 with -1.

  • @Otavioaugusto You added two more rows and two columns?

  • @Liquidpenguin Yes, for the case N = 5, the matrix should be 7x7, but she stays 6x6.

  • The problem is when I do tabuleiro = new int*[N] And then I do the go-around to allocate an array to each pointer and then print out, exactly the matrix N x N appears. To be honest, I’ve never dynamically allotted memory that way. I’ve always used the malloc() and the sizeof, but I was testing for this case and also gave compilation errors.

  • I found out what was wrong. My for’s were like this: for(int i = 0; i <= N; i++). And when I declare the board to be N+2 x N+2, its last position will be the 6. However, my for’s only go up to 5, so the last row and column are missing to be defined as -1. So I must walk to the position N+1.

Show 2 more comments

Browser other questions tagged

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