//A
char** board_ar = newchar*[rows];
for(int i=0; i<rows; ++i)
board_ar[i] = newchar[cols];
board_ar[r][c]; //access cell at row `r', col `c'
//releasing the memory
for(int i=0; i<rows; ++i)
delete [] board_ar[i];
delete [] board_ar;
//B
char **board_ar = newchar*[rows];
board_ar[0] = newchar[rows*cols];
for (int K=1; K<rows; ++K)
board_ar[K] = board_ar[0] + K*cols;
board_ar[r][c]; //access cell at row `r', col `c'
//releasing the memory
delete [] board_ar[0];
delete [] board_ar;
//C
std::vector< std::vector<char> > board_ar (rows, std::vector<char>(cols));
board_ar[r][c]; //access cell at row `r', col `c'
//automatic memory management
//D
std::vector <char> board(rows*cols);
board[r*cols + c]; //access cell at row `r', col `c'
notice the differencea in the memory layout
in B and D, you have one big chunk with all the cells, the rows are contiguous (the cell b[K][cols-1] is next to b[K+1][0])
in A and C every row is a separated chunk
I tried implementing your //B solution, and I'm getting a segmentation fault, and I'm not really sure what the meaning of this is, and how to get around it.
I think it has something to do with allocating memory on the heap, but I don't know why this would be a problem in the code I have.
can't reproduce, ¿what parameters are you using?
also
- your program is incomplete, it's missing the main()'s closing brace
- you just reserve memory, never put any value in the cells. For example, with
I think it's working now. I was just forgetting to put in command line arguments.
Thank you for also pointing out that my code is only reserving memory.