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.
i
andj
will never be 0 orN
.– Mário Feroldi
@Márioferoldi Thanks. I copied his for without modifying.
– Penachia
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
.– Otavio Augusto
@Otavioaugusto You added two more rows and two columns?
– Penachia
@Liquidpenguin Yes, for the case
N = 5
, the matrix should be7x7
, but she stays6x6
.– Otavio Augusto
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 themalloc()
and thesizeof
, but I was testing for this case and also gave compilation errors.– Otavio Augusto
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 beN+2 x N+2
, its last position will be the6
. 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 positionN+1
.– Otavio Augusto