Newsgroups: comp.lang.c
Path: utzoo!utdoe!david
From: david@doe.utoronto.ca (David Megginson)
Subject: Re: Genralizing Pointer Routines
Message-ID: <1990Dec12.002520.25210@doe.utoronto.ca>
Organization: Dictionary of Old English Project - U of Toronto
References: <cbN7yBm00UhW45Cnh2@andrew.cmu.edu>
Date: Wed, 12 Dec 90 00:25:20 GMT

In article <cbN7yBm00UhW45Cnh2@andrew.cmu.edu> rg2c+@andrew.cmu.edu (Robert Nelson Gasch) writes:
>I have a question concerning dynamically allocated data structures. An
>aquaintance told me this was possible, but did now know the deatils.
>
>In PASCAL, if you have 3 linked lists of different pointer types,
>you have to write 3 different Insert, search & delete routines; one
>for each pointer type. I was wondering if these routines can be 
>generalized for any pointer type in C? This would mean that you
>could write each routine only once, which would then operate on all
>3 pointer types. If this can be done, what are the details involved??
>
>Thanx ---> Rob

One trick which I know is to define a generic structure or two to
get at linked-list pointers. For example,

struct list1 {
	struct list1 * next;
};

struct list2 {
	struct list2 * next;
	struct list2 * prev;
};

Now, you can write functions to deal with any arbitrary linked list
of structures, as long as the links are always the first element of
the structures. For example, you could have a linked list of these
structures:

struct record {
	struct record * next;
	char name[NAMEMAX];
	char address[ADDRMAX];
	int age;
	long salary;		/* wishful thinking! */
};

and your linked-list functions would deal with lists of this structure
as if it were (struct list1). This works fine for inserting or deleting
in linked lists, or for freeing lists (free() knows how much memory
to free). Enjoy!


David Megginson
-- 
////////////////////////////////////////////////////////////////////////
/  David Megginson                      david@doe.utoronto.ca          /
/  Centre for Medieval Studies          meggin@vm.epas.utoronto.ca     /
////////////////////////////////////////////////////////////////////////
