
Pointers/Arrays of structures anyone??
: I have just opened a huge can of worms on the best, most readable and
: efficient way to solve the following problem:
: Basically, a function is called which can return either:
: a) an array of structures or
: b) a single structure
Well then, the function actually returns (a pointer to) an array of
structures, of length N.
: of the type, say:
: struct {
: char name[20];
: char street[20];
: char city[20];
: }
: When calling the function another variable is passed which will be
: either a specific 'name' or the character string "ALL", thus the
: function will return either the structure for the name entered or an
: array of structures for all names. It is not known how many names will
: be returned using "ALL", though the MAXIMUM number of names is known.
Then you are going to have to allocate memory in the function, and
return a pointer to the array.
: The question is:
: What is the best way to allocate and handle the memory for maximum
: efficiency? Will it be easier to allocate and clear space for the
: maximum number of records and just return an array of structures, even
: if there is only one? Or will some clever pointer stuff be more
: efficient?
No, just malloc enough memory for however many elements you are
returning. You can either add a terminating marker at the end of
the array, or pass a pointer to the array size to the function
and update this before exiting. (Or various permutations of the
above). Don't forget to free the memory in the main program.
Will