In my code, there is a binary tree struct defined as :
typedef struct bintreestruct *bintree;
struct bintreestruct
{
double num;
char *s;
bintree l, r;
};
I wanted to insert a node into this binary search tree. Here is the function:
void insbintree(double i, char *s, bintree *t)
{
if (t == NULL)
{
bintree temp = (struct bintreestruct *)malloc(sizeof(struct bintreestruct));
temp->s = s;
temp->num = i;
temp->l = temp->r = NULL;
return temp;
}
if (strcmp(s, t->s) < 0)
t->l = insert(t->l, s);
else if (strcmp(s, t->s) >= 0)
t->r = insert(t->r, s);
return t;
}
I am getting the error error: ‘*t’ is a pointer; did you mean to use ‘->’? 62 | if (strcmp(s, t->s) < 0)
Either I am creating the new node incorrectly or accessing the elements inside in
the wrong way using pointers. Not sure how to correct this error
CodePudding user response:
You're hiding a pointer in the typedef :
typedef struct bintreestruct *bintree;
Thus,
void insbintree(double i, char *s, bintree *t)
Here, the variable t
is a pointer to a pointer.
You could choose rename the function prototype to :
void insbintree(double i, char *s, bintree t)
CodePudding user response:
It seems you are trying to write a recursive function because it calls itself.
As the function has return statements with expressions then its return type shall not be void
.
Also this parameter declaration bintree *t
is equivalent to struct bintreestruct **
due to this typedef
typedef struct bintreestruct *bintree;
But within the function you are trying to use it as having the type struct bintreestruct *
.
And in these calls of the function itself
t->l = insert(t->l, s);
t->r = insert(t->r, s);
there are used incomplete and not correctly ordered lists of arguments.
Taking all this into account the function can be declared and defined at least the following way
bintree insbintree(double i, char *s, bintree t)
{
if (t == NULL)
{
t = malloc( sizeof( struct bintreestruct ) );
t->s = s;
t->num = i;
t->l = t->r = NULL;
}
else if ( strcmp(s, t->s) < 0 )
{
t->l = insert(i, s, t->l);
}
else
{
t->r = insert(i, s, t->r );
}
return t;
}
Pay attention to that using the typedef declaration for the pointer type is a bad idea. It only confuses readers of the code.