I'm not sure why you have to use a practically untyped return value using void*
, but let's suppose that there are reasons for it.
There are actually two issues, namely creating the array and using it then.
When creating an array of different types based on some logic, you somehow have to deal with if
or switch()
; how else would you express the logic determining the desired result type? But, if you like, you could also use something like result = malloc(nrOfItems*sizeOfItem)
, and determine sizeOfItem
on any logic you like, even based on arithmetic calculations.
The more interesting or critical thing is how the caller shall use the result of the respective function, as accessing the elements of an array requires knowledge about the type or the size of the elements in it.
Suppose, for example, the following code:
void* getSomeItems() {
if (std::rand() > 100000)
return new char[200];
else
return new double[200];
}
int main() {
void* someItems = getSomeItems();
double c = ((double*)someItems)[199]; // Critical!
// how shall we know if element type is double?
// if rand() decided to create items of type char,
// this code accesses non allocated memory
...
So, unless your function can give back the information on which type has been created (and actually also the size of the array), the return value is almost needless.
I'd suggest not to use void*
for this. If you know the type before calling the function, you could use templates, vectors, or other things. If you do not know type and/or size before calling, return a structure that - besides the allocated array - also provides type/size information.
BTW: do not forget to delete[] / free
the result at the end.