Nested problem structure - reprint

Problems nested structure

Structure of the self-reference (Reference Self) , that is, the internal structure comprising a pointer type structure itself.

Structure refer to each other (Mutual Reference) , that is to say in a plurality of the structures, it contains a pointer to another structure.

1. The self-referential structure

1.1  When not in use typedef

Wrong way:

struct tag_1{
    struct tag_1 A;  
    int value;
};

        This statement is wrong , because this statement is actually an infinite loop, A is a member of a structure, there will be internal A member of a structure, turn down, wireless loop. When memory allocation, since the infinite nesting, can not determine the length of the structure, so this approach is illegal.

Right way:  (using a pointer )

struct tag_1{
    struct tag_1 *A; 
    int value;
};

        Since the length of the pointer is determined (on 32-bit machines pointer length of 4), the compiler is able to determine the length of the structure.

1.2 Use typedef

Wrong way:

typedef struct {
    int value;
    NODE *link; 
} NODE;

  这里的目的是使用typedef为结构体创建一个别名NODEP。但是这里是错误的,因为类型名的作用域是从语句的结尾开始,而在结构体内部是不能使用的,因为还没定义。

正确的方式:有三种,差别不大,使用哪种都可以。

复制代码
typedef struct tag_1{
    int value;
    struct tag_1 *link; 
} NODE;


struct tag_2;
typedef struct tag_2 NODE;
struct tag_2{
    int value;
    NODE *link;   
};


struct tag_3{
    int value;
    struct tag_3 *link; 
};
typedef struct tag_3 NODE;
复制代码

 

2. 相互引用 结构体

错误的方式:

复制代码
typedef struct tag_a{
    int value;
    B *bp; 
} A;

typedef struct tag_b{
    int value;
    A *ap;
} B;
复制代码

       错误的原因和上面一样,这里类型B在定义之前 就被使用。

正确的方式:(使用“不完全声明”)

复制代码
struct tag_a{
    struct tag_b *bp; 
    int value;
};
struct tag_b{
    struct tag_a *ap;
    int value;
};
typedef struct tag_a A;
typedef struct tag_b B;



struct tag_a;  
struct tag_b;
typedef struct tag_a A;
typedef struct tag_b B;
struct tag_a{
    struct tag_b *bp; 
    int value;
};
struct tag_b{
    struct tag_a *ap;
    int value;
};
复制代码

 

嵌套结构体时应注意:

结构体的自引用中,如下这种情况是非法的
struct s_ref {
 int a;
 struct s_ref b;
 char c;
};
因为结构体内部又包含自身结构体类型b,这个长度不能确定,只能向下再查找,又包含自身结构体类型b,又再向下查找,如此循环,类似于永无出口的递归调用,是非法的。

但很多时候,的确需要使用到自引用,有个技巧,如下:
struct s_ref {
 int a;
 struct s_ref *b;  //注意这句与上面相同位置的区别
 char c;
};
这是合法的,因为此处是定义了一个指向结构体的指针,指针的大小在具体的机器平台和编译器环境中都是已知的(即使不同的平台环境的定义不完全相同)。所以不会导致上述的递归死循环。是合法和可行的。但是要提醒的是:这个指针看似指向自身,其实不是,而是指向同一类型的不同结构。
链表和树的数据结构就都使用到此技巧。自身的结构体指针指向下一节点或者下一子树的地址。

这里有一种情况值得注意:
typedef struct {   //这里是结构体类型定义
 int a;
 s_ref *b;  //注意这句引用了结构体类型名
 char c;
}s_ref ;
这个结构体类型定义是为了定义类型名s_ref,但却失败了。因为结构体中就引用了结构类型名,而此时还没定义类型名。
可以改为如下:
typedef struct s_ref_t{   //这里是结构体类型定义和结构体标签
 int a;
 struct s_ref_t *b;  //注意这句与上面相同位置的区别,使用了标签
 char c;
}s_ref ;
这里将运行良好。

发布了33 篇原创文章 · 获赞 2 · 访问量 8508

Guess you like

Origin blog.csdn.net/QQ960054653/article/details/76082868