I’m currently making a small library which can access random.org and get random strings or integers. I’ve run into a slight problem now though, design wise, and I can’t decide which of my two approaches that would be the best, so I will write down my thoughts about both and ask the questions that I find relevant to both.
I currently have a struct like this:
typedef struct {
char **array;
size_t row;
size_t col;
size_t size;
} MemoryStruct;
And this is the source of my “problem”, as I now have added in integer handling into my library.
As it can be seen, the pointer is currently a char pointer, and as I want to be able to handle blot integers and chars, should I add another pointer – an integer pointer – or should I instead make it a void pointer and make a function that will return the correct type of pointer?
The addition of an integer pointer would be the easiest, but I’m not sure how obvious it would seem to the guy who might use my library at some point in the future, that this is why his program segfaults, because he used the wrong pointer in the struct.
However, adding in a void pointer instead means that I will have to do a context based function that will return a pointer of the correct type (if this is even possible – I quite honestly don’t know if it is), which leads to the question:
Which return type would a function that can return different kinds of pointers have? (… it’s obvious, a void pointer!) but then I still don’t have the wanted type included for easy use for the programmer who’re using my library – here is it put into pseudo code what I would like to do.
pointer-with-type-info *fun(MemoryStruct *memory, RandomSession *session)
switch case on session->type
return pointer of appropriate type
It should be added here, that from session->type it can inferred which type the pointer should be.
Thank you in advance for reading this.
The way I understood your question, you know the pointer data type. I would use a
void*instead of two pointers, because you may add more data types later without creating more fields.To retrieve the correct value, one can create two functions:
int getAsString(MemoryStruct, char** value)andint getAsInteger(MemoryStruct, int &value). These functions would return a non-zero value in case of success (true). This way, you will be able no only to retrieve the correct value, but also you will have a way to know whether the value can be retrieved at as this data type.