Pointers Segmentation fault
Oct 9, 2015 at 1:37am UTC
I don't understand why i get a segmentation fault when setting the pointer to the the S(outh) tile, but not for any of the other directions. Could someone help point me in the right direction..
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <time.h>
#include "warp.h"
#include "color.h"
using namespace std;
namespace warp {
// Allocate memory for the board, and set its pointers to adjacent cells.
void init_board(struct tile ****board) {
(*board) = (struct tile ***) malloc(Y*sizeof (struct tile **)); //rows
for (int i=0; i<=Y; i++) {
(*board)[i] = (struct tile **) malloc(X*sizeof (struct tile *)); //cols
for (int j=0; j<=X; j++) {
(*board)[i][j] = (struct tile *) malloc(sizeof (struct tile)); //grid
if (i==Y || j==X || i==0 || j==0) { //walls
(*board)[i][j]->is_wall=true ;
}
else {
(*board)[i][j]->N=(*board)[i-1][j];
//(*board)[i][j]->S=(*board)[1+i][j]; //segmentation fault occurs
(*board)[i][j]->E=(*board)[i][j+1];
(*board)[i][j]->W=(*board)[i][j-1]; }
}
}
}
Oct 9, 2015 at 1:46am UTC
Good grief! Why is this necessary?!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
tile *init_board(){
tile *ret = new tile[X * Y];
for (int i = 0; i < Y; i++){
for (int j = 0; j < X; j++){
if (i == Y - 1 || j == X - 1 || i == 0 || j == 0)
board[i * X + j].is_wall = true ;
else {
board[i * X + j].N = board + ((i - 1) * X + j);
board[i * X + j].S = board + ((i + 1) * X + j);
board[i * X + j].E = board + (i * X + (j + 1));
board[i * X + j].W = board + (i * X + (j - 1));
}
}
}
}
Last edited on Oct 9, 2015 at 1:46am UTC
Topic archived. No new replies allowed.