[comp.lang.c] Turbo C far pointer problem

jcl@lingua.cltr.uq.OZ.AU (Jean-Claude Lacherez) (12/31/90)

When I do not have constants to dimension conventional arrays,
e.g. when I want to do dynamic dimensioning, I use the following trick:


	int	maxrows, maxcols;
	char	**array;

	maxrows = ...whatever...
	maxcols = ...whatever...

	array = (char **) malloc(maxcols * sizeof(char *));

	for(x=0; x < maxrows; x++)
		array[x] = (char *) malloc(maxrows);


	Thereafter, I can use <array> as a normal 2-dimension array,
like <strcpy(array[x], astring);> or <array[x][y] = achar;>, etc...

Now my problem:  This works fine on a Unix system.
Using Turbo C in PC DOS it works fine also as long as I stick to a
small or medium memory model.  But it goes wayward with the large
model.  It is obvious that it has to do with far pointers.  However
I cannot find the logic of it, and after trying all possible (?)
contorsions with type casting I cannot make it work at all.

I would be grateful for any help.

	Jean-Claude Lacherez
	jcl*lingua.cltr.uq.oz.au

marwk@levels.sait.edu.au (01/02/91)

>       int     maxrows, maxcols;
>       char    **array;
>
>       maxrows = ...whatever...
>       maxcols = ...whatever...
>
>       array = (char **) malloc(maxcols * sizeof(char *));

Use maxrows in the above line.

>
>       for(x=0; x < maxrows; x++)      /* !!! do not change this line */
>               array[x] = (char *) malloc(maxrows);

Use maxrows in the above line


Your first malloc allocates MAXCOLS column pointers.
The second allocates MAXROWS rows for MAXROWS columns, not MAXCOLS columns.

The usual matrix use requires array[r][c] to refer to the r'th row and the
c'th column - the changes above will fix this.

Perhaps your UNIX program has a bug it in now?  ;-)

I have tested my solution with TC 2.01.

Ray