There are a few things going wrong here.
1. Nothing to hold the reference to the function you pick.
This;
void* GetNewTree();
Does not declare a function pointer, it's a forward declaration of a method that's not yet defined.
What you want to do instead is change that to a variable of type function pointer, that points to a function matching the GetNewTreeChar/Int function.
Tree* (*GetNewTree)();
That might look weird but that's the syntax for a function pointer.
2. Taking a pointer to the pointer when you want the function.
This;
(Tree*)GetNewTree = &GetNewTreeInt()
;
Does not need the & before the GetNewTreeInt, also you don't want the () at the end of it, as that is calling the method and you don't want that at that point, you want to assign the address of the function to the
GetNewTree
variable.
3. Casting an l-value.
It makes no sense to cast
GetNewTree
to
(Tree*)
, you cast on assignment, not the assigned value.
I think something like this is closer to what you want;
#include <stdio.h>
#include <stdlib.h>
typedef struct Tree {
void *data;
struct Tree *left;
struct Tree *right;
} Tree;
Tree* (*GetNewTree)();
Tree* GetNewTreeInt(){
Tree* newTree = (Tree*)malloc(sizeof(Tree));
newTree->data = malloc(sizeof(int));
newTree->left = newTree->right = NULL;
return newTree;
}
Tree* GetNewTreeChar(){
Tree* newTree = (Tree*)malloc(sizeof(Tree));
newTree->data = malloc(sizeof(char));
newTree->left = newTree->right = NULL;
return newTree;
}
int main() {
int choose;
int number;
scanf("%d", &choose);
switch (choose){
case (0) : GetNewTree = GetNewTreeInt;
break;
case (1) : GetNewTree = GetNewTreeChar;
break;
}
Tree* myTree = GetNewTree();
return 0;
}
Hope this helps,
Fredrik