Do you expect memset(grid,0x0,sizeof(grid));
not to zero the pointer values you've just assigned to grid[0]
through to grid[599]
? If so, you should test that theory by inspecting the pointer values of grid[0]
through to grid[599]
before and after that call to memset
, to find out what memset
does to true (more on that later) arrays.
Your program is dereferencing a null pointer which results directly from that line of code. Typically, a crash can be expected when you attempt to dereference a null pointer, because null pointers don't reference any objects. This explains your observation of a crash, and your observation of the crash disappearing when you comment out that call to memset
. You can't expect good things to happen if you try to use the value of something which isn't an object, such as grid[1][...
where grid[1]
is a pointer consisting entirely of zero bits.
The term 3D array doesn't mean what you think it means, by the way. Arrays in C and C++ are considered to be a single allocation, where-as what your code is producing seems to be multiple allocations, associated in a hierarchical form; you've allocated a tree as opposed to an array, and memset
isn't appropriate to zero a tree. Perhaps your experiments could be better guided from this point on by a book regarding algorithms, such as Algorithms in C, parts 1-4 by Robert Sedgewick.
For the meantime, in C, the following will get you a pointer to a 2D array which you can mostly use as though it's a 3D array:
void *make_grid(size_t x, size_t y, size_t z) {
int (*grid)[y][z] = malloc(x * sizeof *grid);
/* XXX: use `grid` as though it's a 3D array here.
* i.e. grid[0][1][2] = 42;
*/
return grid;
}
Assuming make_grid
returns something non-null, you can use a single call to memset
to zero the entirety of the array pointed to by that function because there's a single call to malloc
matching that a single call to memset
... Otherwise, if you want to zero a tree, you'll probably want to call memset
n times for n items.
In C++, I don't think you'll find many who discourage the use of std::vector
in place of arrays. You might want to at least consider that option, as well as the other options you have (such as trees; it seems like you want to use a tree, which is fine because trees have perfectly appropriate usecases that arrays aren't valid for, and you haven't given us enough context to tell which would be most appropriate for you).