Hi,
Note: Sorry, I can't get the indenting to work properly!
Let me start off by saying I'm an entirely self taught programmer (although I'm not sure it's accurate or fair to describe myself as a programmer), so there may be some stylistic issues presented in the code below. If you have any comments / suggestions as to how to improve the follow bit of code in general, I'd appreciate it. However, I have a specific question regarding a compiler warning that I find confusing.
The following code compiles and runs as I expect it to, yet I generate a number of 'passing argument from incompatible pointer type' errors, and I'd like to know what I'm doing wrong. I'm concerned that while it currently appears to be doing what I want it to do, that it's actually only working by chance (i.e. the code works, but for the wrong reasons), which would mean it would potentially break in the future.
I'm compiling using gcc 4.03 on OS X 10.6.2, though I haven't tried to run this through Xcode directly.
Here is the code:
typedef struct
{
int data;
int depth;
struct node *parent_ptr;
struct node *left_ptr;
struct node *right_ptr;
} node;
node *addNode(node *n, node* nprev, int data, int depth, int maxdepth)
{
if (n==NULL && depth < maxdepth)
{
printf("null pointer found, creating node.\tdepth = %d\n", depth);
n= calloc(1, sizeof(node));
n->data= data;
n->depth= depth;
if (n->left_ptr == NULL)
{
n->left_ptr= addNode(n->left_ptr, n, n->data*2, n->depth+1, maxdepth);
}
if (n->right_ptr == NULL)
{
n->right_ptr= addNode(n->right_ptr, n, n->data*2+1, n->depth+1, maxdepth);
}
}
return n;
}
Compiling returns the error passing argument 1 of ‘addNode’ from incompatible pointer type from the line
n->left_ptr= addNode(n->left_ptr, n, n->data*2, n->depth+1, maxdepth);
I'm not sure why. n->left_ptr, is a pointer, and the definition of addNode is node *addNode(node *n, node* nprev, int data, int depth, int maxdepth), so it should be expecting a pointer to a node, which is exactly what I'm passing it.
Is it because I'm passing a pointer to a pointer, in which case the definition should be
*addNode(node **n, node **nprev, int data, int depth, int maxdepth),
and then when I call it with a single pointer, include a dereferencing &?
Cheers,
Brad