5 /*******************************************************************
6 create a matrix of any dimension. The return must be cast correctly.
7 ********************************************************************/
8 void *any_matrix(int dimension, int el_size, ...)
12 int i,j,size,ptr_size,ppos,prod;
17 if (dimension <= 0) return(NULL);
18 if (el_size <= 0) return(NULL);
20 dims = (int *)malloc(dimension * sizeof(int));
21 if (dims == NULL) return(NULL);
23 /* gather the arguments */
24 va_start(ap, el_size);
25 for (i=0;i<dimension;i++) {
26 dims[i] = va_arg(ap, int);
30 /* now we've disected the arguments we can go about the real
31 business of creating the matrix */
33 /* calculate how much space all the pointers will take up */
35 for (i=0;i<(dimension-1);i++) {
37 for (j=0;j<=i;j++) prod *= dims[j];
41 /* padding overcomes potential alignment errors */
42 padding = (el_size - (ptr_size % el_size)) % el_size;
44 /* now calculate the total memory taken by the array */
46 for (i=0;i<dimension;i++) prod *= dims[i];
47 size = prod + ptr_size + padding;
49 /* allocate the matrix memory */
50 mat = (void **)malloc(size);
53 fprintf(stdout,"Error allocating %d dim matrix of size %d\n",dimension,size);
58 /* now fill in the pointer values */
59 next_ptr = (void *)&mat[dims[0]];
62 for (i=0;i<(dimension-1);i++) {
64 if (i == dimension-2) {
65 skip = el_size*dims[i+1];
66 next_ptr = (void *)(((char *)next_ptr) + padding); /* add in the padding */
68 skip = sizeof(void *)*dims[i+1];
71 for (j=0;j<(dims[i]*prod);j++) {
72 mat[ppos++] = next_ptr;
73 next_ptr = (void *)(((char *)next_ptr) + skip);
89 x = (double ****)any_matrix(4, sizeof(double), 3, 6, 8, 2);