[comp.sys.mac.programmer] THINK C 4.0 and arrays

AGRAWAL@rcgl1.eng.ohio-state.edu (Rajiv Agrawal) (12/04/89)

Hi,
   I have run into a small C problem on the Mac that I cannot fix.  Can someone
help me?  I am posting the segment from the program.  This program allocates a
matrix.  But the matrix entries change arbitrarily when I try to update the
matrix.  I have seen some discussions on HLock and memory management on the Mac
and that might be the source of the trouble.  I took the matrix allocation
routine from Numerical Recipes in C book and it works correctly on the VAX.
I am using THINK C 4.0 on a Mac II System 6.0.2.

Thanks in advance.

Rajiv.
------------------------------------------
#include <stdio.h>
#include <stdlib.h>

main()
{

	int		i,j,n;
	float	**hessin;
	float	**matrix();

	n=2;
	/* work space */
	hessin = matrix(1,n,1,n);

	/* initialize to a unit matrix */
	for (i=1;i<=n;i++) {
		for (j=1; j<=n; j++)
			hessin[i][j]=0.0;
		hessin[i][i]=1.0;
	}

	printf("Old matrix\n");
	for(i=1;i<=2;i++)
		printf("%f %f\n",hessin[i][1],hessin[i][2]);

	/* Add 2.0 to all the elements of the matrix */
	for (i=1;i<=n; i++)
		for (j=1; j<=n; j++)
			hessin[i][j] += 2.0;     /* BUGGY statement .... the second row of the
                    matrix changes upon the first execution of this statement */

	printf("New matrix\n");
	for(i=1;i<=2;i++)
		printf("%f %f\n",hessin[i][1],hessin[i][2]);
}

/* Numerical recipes in C */
float **matrix(nrl,nrh,ncl,nch)
int	nrl,nrh,ncl,nch;
/* Allocates a float matrix with range [nrl..nrh][ncl..nch] */
{
	int	i;
	float **m;

	/* Allocate pointers to rows */
	m=(float **) malloc((unsigned) (nrh-nrl+1)*sizeof(float*));

	/* Allocate rows and set pointers to them */
	for (i=nrl;i<=nrh;i++) {
		m[i]=(float *) malloc((unsigned) (nch-ncl+1)*sizeof(float));
		m[i] -= ncl;
	}

	/* return pointer to array of pointers to rows */
	return m;
}
----------------------------------------------------------------------
Rajiv Agrawal      (614) 292-9029     (614) 421-7970
206 W 18th Ave, Columbus, OH 43210             BITNET: TS5600@OHSTVMA
INTERNET: agrawal@rcgl1.eng.ohio-state.edu   rajiv@felix.eng.ohio-state.edu
          agrawal@porsche.eng.ohio-state.edu

Being an Indian, I prefer to work 8-5 Indian Standard Time.

AGRAWAL@rcgl1.eng.ohio-state.edu (Rajiv Agrawal) (12/05/89)

Hi,
   Please ignore my previous message.  As someone pointed out, I was missing
the line:

m -= nrl;

after the allocation of the matrix.

Rajiv.
----------------------------------------------------------------------
Rajiv Agrawal      (614) 292-9029     (614) 421-7970
206 W 18th Ave, Columbus, OH 43210             BITNET: TS5600@OHSTVMA
INTERNET: agrawal@rcgl1.eng.ohio-state.edu   rajiv@felix.eng.ohio-state.edu
          agrawal@porsche.eng.ohio-state.edu

Being an Indian, I prefer to work 8-5 Indian Standard Time.