When you allocate something[a][b] is it contiguous?
Yes
When I made games that had tiled maps I would even access a tile using a pointer in rendering.
Ie: if the map was 10x10, I would render tile [1][3] by using arrayName[14]
for example.
Also keep in mind using that fact, that in some places, [b] instead of [a] is what will be completely on the memory, this might cause bugs if you are relying on code that came from FORTRAN (like CBLAS) or in some specific devices and situations (like some GPU with some particular drivers).
When you use malloc, it must be contiguous?
Yes, and it will fail if contiguous memory is not available.
It is a very common mistake to expect that a program will work because the total free memory exists, without taking in account memory fragmentation.
I made once a game that failed to work because it had 30mb of memory but could not load a 16mb image... I did not realised at the time that memory fragmentation caused by my code was making no block of 16mb be available.
If there are no need for dynamic allocation, I should use stack or heap?
In C, dynamic allocation usually means heap allocation anyway, early C books even explicitly say that malloc
and similar family of functions (calloc
included) operate only on the heap. while automatic allocation attempts to use the stack.