在我的代碼中,有一個二叉樹結構定義為:
typedef struct bintreestruct *bintree;
struct bintreestruct
{
double num;
char *s;
bintree l, r;
};
我想在這個二叉搜索樹中插入一個節點。這是功能:
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;
}
我收到錯誤 error: ‘*t’ is a pointer; did you mean to use ‘->’? 62 | if (strcmp(s, t->s) < 0)
我錯誤地創建新節點或
使用指標以錯誤的方式訪問內部元素。不知道如何糾正這個錯誤
uj5u.com熱心網友回復:
您似乎正在嘗試撰寫遞回函式,因為它會呼叫自己。
由于該函式具有帶有運算式的回傳陳述句,因此其回傳型別不應為void.
由于此 typedef,此引數宣告bintree *t也等效于struct bintreestruct **
typedef struct bintreestruct *bintree;
但是在函式中,您嘗試將其用作具有 type struct bintreestruct *。
在函式本身的這些呼叫中
t->l = insert(t->l, s);
t->r = insert(t->r, s);
使用了不完整且未正確排序的引數串列。
考慮到所有這些,至少可以通過以下方式宣告和定義函式
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;
}
請注意,對指標型別使用 typedef 宣告是一個壞主意。它只會讓代碼的讀者感到困惑。
uj5u.com熱心網友回復:
您在 typedef 中隱藏了一個指標:
typedef struct bintreestruct *bintree;
因此,
void insbintree(double i, char *s, bintree *t)
這里,變數t是指向指標的指標。您可以選擇將函式原型重命名為:
void insbintree(double i, char *s, bintree t)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/457191.html
