MATLAB: How to create a multidimensional matrix with variable dimension sizes in C for the MATLAB Compiler

ccreatecreatingdeclarationdeclareMATLABmatrixmulti-dimensional

When I try to declare a matrix in C as having dimensions specified by a variable, I get an error message from the C compiler:
integer expression must be constant
where the integer referred to is a matrix dimension.
The problem is that I do not know the matrix dimension until run-time.
#include "mex.h"
#include <stdio.h>
/******* ROUTINE *******/
void func(int z)
{
double A[z][5]; /* HERE'S THE PROBLEM: WANT TO MAKE MATRIX z-by-z, not 5-by-5 */
printf("z=%d\n", z);
}
/******* GATEWAY FUNCTION HERE TO LINK C & MATLAB **************/
void mexFunction(
int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
{
int z;
/* get scalar data from Matlab input */
z = mxGetScalar(prhs[0]);
/* call the C subroutine */
func(z);
}

Best Answer

The declaration of a variable multidimensional array like the one below is illegal in C:
double A[z][5]; /* ILLEGAL */
If you wish to create a multidimensional array of variable size, you will have to declare a pointer to an array of pointers and then allocate memory dynamically, as shown below:
double** func (int x, int y)
{
double **A;
int i;
/*allocates dynamic memory and returns a pointer to an array of double pointers*/
A = (double **) malloc( x * sizeof(double *));
/*allocates memory for each element of the array of double pointers*/
for (i = 0; i < x ; i++ )
A[i] = (double *) malloc( y * sizeof(double));
printf("x = %d\n", x);
printf("y = %d\n", y);
/* deallocate the memory */
for (i = 0; i < x ; i++ )
free(A[i]);
free(A);
}