问题
I need to figure out how to pass two different structs to a function. I tried using void * for the parameter but i am receiving the error:
warning: dereferencing 'void *' pointer
error: request for member left in something not a structure or union
same error for member right
here is what i did in general terms(code may not compile).
struct A{
char *a;
struct A *left, *right;
} *rootA;
struct B{
char *b;
struct B *left, *right;
} *rootB;
void BinaryTree(void *root, void *s){
if(condition)
root->left=s;
else if(condition)
BinaryTree(root->left, s);
if(condition)
root->right=s;
else if(condition)
BinaryTree(root->right, s);
}
int main(){
// Assume the struct of nodeA and nodeB get malloc()
// as well as the variables a and b with actual data.
struct A nodeA;
struct B nodeB;
BinaryTree(rootA, nodeA);
BinaryTree(rootB, nodeB);
return 0
}
回答1:
You are confused on your struct declarations. The type is given by the word after struct. That thing at the end needs to go, at least until you learn about typedefs. Example:
struct A{
char *a;
struct A *left, *right;
};
When you call BinaryTree you need to always pass it pointers not structs. Example:
BinaryTree(&nodeA, &nodeA);
When you do operations on a void pointer, you need to cast it to the correct pointer type first. Example:
(struct A*)root->left=s;
Passing these structs around as void pointers is definitely bad practice and you will get yourself horribly confused. Void pointers are to be used sparingly. Since you seem to be starting on C, I recommend you don't use them at all yet until you understand value and reference semantics a little better. That being said, I made lots of stupid code when I started on C, still do sometimes. You'll figure it out with time and practice.
回答2:
There are 2 aspects of your program which needs to be relooked. One, is the parameter passing where you are passing by value and not reference. Hence, the calls for BinaryTree
function should have
BinaryTree(rootA, &nodeA);
The other major consideration is how you handle these void pointers in the BinaryTree
function. In the current form,
void BinaryTree(void *root, void *s){
if(condition)
root->left=s;
Here root
is a void *
and hence, root->left
can't be evaluated. Hence, you need to typecast root
to a meaningful data type like
struct A *hdl = (struct A*)(root);
hdl->left = s;
Even with this approach, one more important consideration is that you are using the same function for different structures. Hence, it would be difficult/challenging to know when to type cast root
as A
vs B
and hence, this strategy requires a small rethink.
来源:https://stackoverflow.com/questions/20230549/passing-different-structs-to-a-functionusing-void