结构指针和结构指针成员的区别

difference between structure pointer and member of structure pointer

我在这里声明一个结构体

struct node
{
  int data;
  struct node *next;
};

我正在用这个声明创建一个指针

struct node *link;

nextlink指针有什么区别还是它们是同一类型的指针?

有一处不同。

link指针可以有初值,但是next指针不能有初值,原因是:

每当我们声明一个结构时,我们都是在声明一个新类型而不是一个新变量。

所以

struct node *link=NULL;

允许,而

struct node
{
  int data;
  struct node *next=NULL;
};

不允许。

struct node
{
  int data;
  struct node *next;
};

struct node *link

*next 和 *link 都是指针,所以它们的大小是一样的。他们指向的数据类型是一样的,结构node。但它们完全不同:

struct node *p = malloc(sizeof (node)); //allocate memory for a new node

//now, p will point to an address.
//p->next is still un-initilized, so we have to assign it an address 

p->next = NULL; 

p, and p->next point to different addressess

所以这两个指针是不同的,相互独立存在。其实*link甚至不一定是指针,可以为一个节点静态分配内存:

struct node p;
p.next=NULL

或者您可以将其他指向节点的指针添加到节点结构,以获得更复杂的数据结构,例如树或双 linked 列表:

struct node
{
   int data;
   struct node* next;
   struct node* prev;
}
struct node
{
  int data;
  struct node *next; // line 1
};

struct node *link; // line 2

第 1 行称为自引用结构,第 2 行只是给定结构的指针变量。 在链表中使用了自引用结构,因为我们想要相同类型的所有节点。假设,如果你声明 struct node *p = malloc(sizeof (node)); 在这里, p 创建了一些 space 并且 space 分为两部分 1. int data 2. *next 。 表示一部分有数据,另一部分有下一个节点的地址。