自指结构

Self referential Structure

本文关键字:结构      更新时间:2023-10-16

我正在为自引用结构编写 2 个代码:

第一:

struct node
{
    int a;
    struct node *link;
};
int main()
{
    struct node n;
    n.a = 5;
    cout<< n.a << "t" ;
    cout << n.link ;
    return 0;
}

输出 : ̀ 5 0x40185b'

第二:

struct node{
    int a;
    struct node *link;
};
int main(){
    struct node n;
    n.a = 5;
    cout << n.a << "t";
    cout << *n.link ;
    return 0;
}

输出:错误:链接未在此范围内声明。

请告诉我代码中到底发生了什么?

为什么抛出垃圾值??

如何初始化自引用结构指针?

我想

这就是你想做的:

int main(){
    struct node n;
    n.a = 5;
    n.link = NULL; // initialize the link
    cout << n.a << "t";
    cout << n.link;
    return 0;
}

仅当n.link指向有效的node对象时,*(n.link)才有效。并且cout << *(n.link);只有在您声明nodeoperator<<时才有效(cout << n.link;有效,因为它输出地址,而不是值)。

例如,这会更好:

#include <iostream>
struct node{
    int a;
    node *link; // Note: no need to prefix with struct
};
std::ostream& operator<<( std::ostream& str, const struct node& n )
{   
    str << n.a << "t -> ";
    if ( n.link )
        str << *n.link;
    else
        str << "NULL";
    return str;
}
int main(){
    node n1; // Note: no need to prefix with struct
    node n2; // Note: no need to prefix with struct
    n1.a = 5;
    n1.link = &n2;
    n2.a = 6;
    n2.link = NULL;
    cout << n1;
    return 0;
}

它输出5 -> 6 -> NULL