Genralizing Pointer Routines

David Megginson david at doe.utoronto.ca
Wed Dec 12 11:25:20 AEST 1990


In article <cbN7yBm00UhW45Cnh2 at andrew.cmu.edu> rg2c+ at 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 at doe.utoronto.ca          /
/  Centre for Medieval Studies          meggin at vm.epas.utoronto.ca     /
////////////////////////////////////////////////////////////////////////



More information about the Comp.lang.c mailing list