Say I have a group of struct's that I want to manage arrays of via blocks of pointers. I would like to initialize these blocks in a generic fashion, and here's what I'm thinking:
enum my_type {STRUCT_1, STRUCT_2, STRUCT_3} ;
struct my_struct_1 {...} ;
struct my_struct_2 {...} ;
struct my_struct_3 {...} ;
void * my_array_init(my_type t) {
void * array = NULL ;
switch(t) {
case STRUCT_whatever :
(my_struct_whatever **) array ; /* does this cast or is assignment needed? */
default :
}
array = malloc(sizeof(*array) * BLOCK_SIZE) ;
if(array) {
for(i=0 ; i<BLOCK_SIZE ; ++i)
array[i] = NULL ;
}
return array ;
}
Then I was thinking I could use it like:
/* Initially set all pointers to NULL */
my_struct_1 ** s1 = NULL ;
my_struct_2 ** s2 = NULL ;
my_struct_3 ** s3 = NULL ;
s1 = my_array_init(STRUCT_1) ;
s2 = my_array_init(STRUCT_2) ;
s3 = my_array_init(STRUCT_3) ;
Am I on a right track, do I have the level of indirection wrong, or should I just bag it and write individual 'init' functions? Regarding 'void *', since it can point to anything I'd think it could be a handle (pointer to pointer), and I've seen conflicting arguments about 'void **'. However, 'void **' does appear in at least one of the examples in K&R 2nd ed. - in '5.11 Pointers to Functions' on page 119. For what it's worth, all the struct's contain only pointers and basic data types.