Dynamic allocation of pointer arrays
Author Message Dynamic allocation of pointer arrays

Thanks to the help from many readers of this news group, I implemented
the program
I want.  I was trying to code a function which takes a 2d array of pointers
pointing to functions returning doubles.  I would also like the 2d array
to begin at any integer index, rather than the C-encouraged value of 0.
Additional, I would like to free the memories used by the array if they are
no longer needed in the latter part of the code.

Appended is the test code I wrote.  Again, thank you all who helped and
inspired me on this code.

---------------------------------------------------------------

double  f1(x)
double  x;
{
return 10.0 + x;

Quote:
}

double  f2(x)
double  x;
{
return 20.0 + x;

Quote:
}

double  f3(x)
double  x;
{
return 30.0 + x;

Quote:
}

double  f4(x)
double  x;
{
return 40.0 + x;
Quote:
}

double  f5(x)
double  x;
{
return 50.0 + x;

Quote:
}

double  f6(x)
double  x;
{
return 60.0 + x;

Quote:
}

typedef double (*dfunction_pointer)();

dfunction_pointer **dfunction_pointer_matrix(nrl,nrh,ncl,nch)
int     nrl,nrh,ncl,nch;
/* allocate a two-dimensional matrix of pointers pointing functions returning
doubles.  The subscript range is m[nrl..nrh][ncl..nch] */
{
int         i;
dfunction_pointer   **m;

/* allocate pointers to rows */
m = (dfunction_pointer **) malloc( (unsigned)
(nrh-nrl+1)*sizeof(dfunction_pointer*) ) - nrl;
if (!m) nrerror("allocation failure 1 in dfunction_pointer_matrix()");

/* allocate rows and set pointers to them */
for(i=nrl;i<=nrh;i++) {
m[i] = (dfunction_pointer *) malloc( (unsigned)
(nch-ncl+1)*sizeof(dfunction_pointer) ) - ncl;
if (!m[i]) nrerror("allocation failure 2 in dfunction_pointer_matrix()");
}
/* return pointer to array of pointers to rows */
return m;

Quote:
}

void free_dfunction_pointer_matrix(m,nrl,nrh,ncl,nch)
dfunction_pointer       **m;
int                     nrl,nrh,ncl,nch;
/* free a two-dimensional matrix allocated by dfunction_poiner_matrix() */
{
int i;

for ( i = nrh; i >= nrl; i-- )
free( (char*) (m[i]+ncl) );
free( (char*) (m+nrl) );

Quote:
}

void    sub( nrl, nrh, ncl, nch, fa, x )
int     nrl, nrh, ncl, nch;
dfunction_pointer **fa;
double  x;
{
int         i, j;

for ( i = nrl; i <= nrh; ++i )
for ( j = ncl; j <= nch; ++j )
printf( "i=%d j=%d x=%f fa=%f\n", i, j, x, fa[i][j](x) );

Quote:
}

main()
{
dfunction_pointer   **fnm;
int         nrl, nrh, ncl, nch;
double      x;

x = 0.5;

nrl = 1;
nrh = 3;
ncl = 3;
nch = 4;
fnm = dfunction_pointer_matrix( nrl, nrh, ncl, nch );

fnm = f1;
fnm = f2;
fnm = f3;
fnm = f4;
fnm = f5;
fnm = f6;

sub( nrl, nrh, ncl, nch, fnm, x );

free_dfunction_pointer_matrix( fnm, nrl, nrh, ncl, nch );

Quote:
}

Sun, 21 Jan 1996 04:21:50 GMT

 Page 1 of 1 [ 1 post ]

Relevant Pages