我想基于以下创建2D数组的代码动态分配3D数组,任何建议都会非常有用:
void** malloc_2d (size_t nrows, size_t ncols, int elementsize) {
size_t i;
void ** ptr;
if ( (ptr = (void**)malloc(nrows * sizeof(void *))) == NULL ) {
fprintf(stderr, "malloc_2d: out of memory\n");
exit(1);
}
if ( (ptr[0] = malloc(nrows * ncols * elementsize)) == NULL ) {
fprintf(stderr, "malloc_2d: out of memory\n");
exit(1);
}
for (i=1; i<nrows; i++)
ptr[i] = (char*)ptr[0] + i * ncols * elementsize;
return ptr;
}
由于