Tested it. Seems to work fine. Just looking at the net I get more complicated results on how to allocate a 3D array. So why not just use a single line??
Tested it. Seems to work fine. Just looking at the net I get more complicated results on how to allocate a 3D array. So why not just use a single line??
It only works if all the minor dimensions are compile time constants, and thus the compiler can work out the size from the declaration of the pointer.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
Why? This works fine:
When I put a large number for maxx, maxxy it crushes though. But it seems to allocate a 3D array with maxx, maxy, maxz not being at constant-time valued.Code:#include <stdlib.h> #include <stdio.h> int main() { int x,y,z; int t; int maxx, maxy, maxz; scanf("%d %d %d", &maxx, &maxy, &maxz); int (*p)[maxy][maxx] = malloc(maxz * sizeof(*p)); for (x=0; x<maxx; ++x) for (y=0; y<maxy; ++y) for (z=0; z<maxz; ++z) t = p[x][y][z]; }
You know Ptolemy's model of planet paths worked to accurately map where celestial bodies should be. Though completely wrong, it did work just fine too.