2D array question

Zev Sero zvs at bby.oz.au
Tue Jul 3 12:58:59 AEST 1990


In article <3336.268f44b2 at cc.nu.oz.au> v8902477 at cc.nu.oz.au writes:

	struct a {
	    int a1, a2, a3;
	};
	array = (struct a *) calloc(xdim*ydim, sizeof(struct a));

and then
	*((array+x+y*ydim).a1) = value;
which doesn't work.



The following:
    (*(array + x + y * ydim)).a1 = value;
or
    (array + x + y * ydim)->a1 = value;
will work.  Adding to a pointer still yields a pointer.

However, try the following instead:
    array = (struct a **) malloc (ydim * sizeof (struct a *);
    for (i = 0; i < ydim; i++)
	array[i] = (struct a *) calloc (xdim, sizeof (struct a));
    ...
    array[y][x].a1 = value;

This will give you the almost-equivalent of declaring 
   struct a array[ydim][xdim];
which you would have done if ydim and xdim were constants.

The differences between the pointer and a proper 2d array are that the
pointer is modifiable, and that if you free the pointer you should
first free each element.  Also, the elements of an array occupy a
contiguous area of memory, and the elements of this pseudo-array might
not, but I don't see what difference that makes.
--
				Zev Sero  -  zvs at bby.oz.au
...but we've proved it again and again
that if once you have paid him the danegeld,
you never get rid of the Dane.		- Rudyard Kipling



More information about the Comp.lang.c mailing list