Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP
Path: utzoo!mnetor!seismo!rutgers!okstate!osubem!walters
From: walters@osubem.UUCP (walters)
Newsgroups: comp.lang.c
Subject: Two dimensional arrays in C (a new approach)
Message-ID: <182@osubem.UUCP>
Date: Sat, 4-Jul-87 21:45:12 EDT
Article-I.D.: osubem.182
Posted: Sat Jul  4 21:45:12 1987
Date-Received: Mon, 6-Jul-87 06:56:51 EDT
Organization: Oklahoma State Univ., Stillwater
Lines: 94
Keywords: array multi-dimensional

What follows is some sample code that demonstrates using an 'array of
pointer to an array of double'.  This is a nice portable way to get
variable dimension arrays (I learned FORTRAsh before I learned C).  It's
great for swapping rows when doing matrix algebra and it also aviods
doing array indexing explicitly.  Obviously it could be used with other
types (ie.  integer).  Hope someone finds this useful. 

#include 
#include 

typedef double *RWP;
typedef struct
{
	RWP rw;
} A;

void do_something(a, r, c)
A a[];
int r, c;
{
	int i, j;
	RWP ai;

	for (i = 0; i < r; i++)
	{
		ai = a[i].rw;
		for (j = 0; j < c; j++)
			ai[j] = -ai[j];
	}
	return;
}

void do_something_else_another_way(a, r, c)
A a[];
int r, c;
{
	int i, j;

	for (i = 0; i < r; i++)
		for (j = 0; j < c; j++)
			a[i].rw[j] = fabs(a[i].rw[j]);
	return;
}

int arr_alloc(a, r, c)	/* allocate the array */
A **a;
int r, c;
{
	register int i, j;
	
	if ((*a = (A *) malloc(r * sizeof(A))) == (A *) NULL)
		return(0);
	for (i = 0; i < r; i++)
	{
		(*a)[i].rw = (RWP) malloc(c * sizeof(double));
		if ((*a)[i].rw == (RWP) NULL)
			return(0);
	}
	for (i = 0; i < r; i++)
		for (j = 0; j < c; j++)
			(*a)[i].rw[j] = 0.0;
	return(1);
}
						
void arr_free(a, r)	/* free the array */
A **a;
int r;
{
	register int i;
	
	for (i = 0; i < r; i++)
		free((*a)[i].rw);
	free(*a);
	return;
}	

#define MSIZE 10

main()
{
	static A *a;

	if (!arr_alloc(&a, MSIZE, MSIZE)) 
		abort();
	do_something(a, MSIZE, MSIZE);
	do_something_else_another_way(a, MSIZE, MSIZE);
	arr_free(&a, MSIZE);
}		

-----
Harold G. Walters                 Internet: walters@ce.okstate.edu
School of Civil Engineering       Uucp: {cbosgd, ihnp4, rutgers, seismo,
Oklahoma State University               uiucdcs}!okstate!osubem!walters
Stillwater, OK  74078