简体   繁体   English

结构中的指针指向另一个结构

[英]Pointers in Structure pointing to another strucutre

I am trying to understand how pointers in linked lists work.我试图了解链表中的指针是如何工作的。 So far i am having lots of trouble trying to figure out where the pointer is pointing to and how a pointer of a type struct works( I know we need to allocate memory from the heap but can't quite understand it, but maybe that's a different question altogether).到目前为止,我在试图弄清楚指针指向的位置以及类型结构的指针如何工作时遇到了很多麻烦(我知道我们需要从堆中分配内存,但不太明白,但也许这是一个完全不同的问题)。

Lets take this structure:让我们采用这种结构:

typedef struct Node {
    int data;
    struct Node *link;
} Node;

What I think will happen now is:我认为现在会发生的是:

  1. Say you have a pointer of type Node in the main function, Node* p and this is allocated memory (using malloc).假设您在主函数Node* p有一个 Node 类型的指针,这是分配的内存(使用 malloc)。

  2. Now if we have some data p->data=5;现在如果我们有一些数据p->data=5; , p points to the beginning of this data (at least this is what i think is happening). , p 指向此数据的开头(至少这是我认为正在发生的事情)。

Where exactly does link point to? link到底指向哪里?

So now, i come across this particular piece of code:所以现在,我遇到了这段特殊的代码:

typedef struct Node {
    int data;
    struct Node *link;
} Node;

typedef struct List {
    Node* head;
    int number_of_nodes;
} List;

So this is complete chaos in my brain!所以这完全是我脑子里的混乱! . .

Now in the structure List , what is head doing?现在在List结构中, head在做什么? What is it pointing to?它指的是什么? And how would you create a linked list at all with these two lists??你将如何用这两个列表创建一个链表?

I am really trying my level best to understand how linked lists work, but all the pointers make it too hard to keep track of.我真的在尽我所能去理解链表是如何工作的,但是所有的指针都很难跟踪。 You might suggest i start with something simple and i did, and i have already mentioned how much i understand.你可能会建议我从一些简单的事情开始,我做到了,而且我已经提到了我的理解程度。 But the head pointer in the second structure has completely thrown me off track!但是第二个结构中的head指针完全让我偏离了轨道!

It would make my life so much more easier if someone could help me explain it while keeping track of the pointers.如果有人可以帮助我解释它,同时跟踪指针,那将使我的生活变得更加轻松。

Where exactly does link point to?链接到底指向哪里?

link points to another object of the same type: link指向另一个相同类型的对象:

+------+------+     +------+------+     +------+------+
| data | link |---->| data | link |---->| data | link | ----> ...
+------+------+     +------+------+     +------+------+

Now in the structure List, what is head doing?现在在结构List中,head在做什么? What is it pointing to?它指的是什么?

head points to the first node in a list: head指向列表中的第一个节点:

+-----------------+     +------+------+     +------+------+ 
| head            |---->| data | link |---->| data | link |----> ...
+-----------------+     +------+------+     +------+------+
| number_of_nodes |
+-----------------+

I am really trying my level best to understand how linked lists work,我真的在尽我所能去理解链表是如何工作的,

Don't feel bad - linked lists threw me for a loop in my Data Structures class (my first "hard" CS class).不要难过 - 链表让我在我的数据结构类(我的第一个“硬”CS 类)中循环。 It took me a solid week longer than my classmates to grok the concept.我花了比我的同学多一周的时间来理解这个概念。 Hopefully the pictures help.希望图片有帮助。

Edit编辑

what happens if you have a pointer to the structure List, memory allocated and all?如果您有一个指向结构 List、分配的内存和所有内容的指针,会发生什么? Where does it point to then (according to the diagrams, which did help by the way)那么它指向哪里(根据图表,顺便说一下)

So, let's assume you have the following code:因此,让我们假设您有以下代码:

/**
 * Create a new list object.  head is initially NULL,
 * number_of_nodes initially 0.
 */
List *newList( void )
{
  List *l = malloc( sizeof *l );
  if ( l )
  {
    l->head = NULL;
    l->number_of_nodes = 0;
  }
  return l;
}

int main( void )
{
  List *l = newList();
  ...
}

Then your picture looks like this:那么你的图片是这样的:

+---------+       +--------------------+
| l: addr | ----> | head: NULL         |
+---------+       +--------------------+
                  | number_of_nodes: 0 |
                  +--------------------+

( addr represents some arbitrary memory address) addr代表一些任意的内存地址)

Now let's say you add a node to your list:现在假设您将一个节点添加到您的列表中:

/**
 * Create a new node object, using the input data
 * link is initially NULL
 */
Node *newNode( int data )
{
  Node *n = malloc( sizeof *n );
  if ( n )
  {
    n->data = data;
    n->link = NULL;
  }
  return n;
}

void insertNode( List *l, int data )
{
  Node *n = newNode( data );
  if ( n )
  {
    /**
     * If list is initially empty, make this new node the head
     * of the list.  Otherwise, add the new node to the end of the
     * list.
     */
    if ( !l->head ) // or n->head == NULL
    {
      l->head = n;
    }
    else
    {
      /**
       * cur initially points to the first element in the list.  
       * While the current element has a non-NULL link, follow
       * that link.
       */
      for ( Node *cur = l->head; cur->link != NULL; cur = cur->link )
        ; // empty loop body
      cur->link = n;
    }
    l->number_of_nodes++;
  }
}

int main( void )
{
  List *l = newList();
  insertNode( l, 5 );
  ...
}

Now your picture looks like this:现在你的图片看起来像这样:

+---------+       +--------------------+      +------------+
| l: addr | ----> | head: addr         | ---> | data: 5    |
+---------+       +--------------------+      +------------+
                  | number_of_nodes: 1 |      | link: NULL |
                  +--------------------+      +------------+

You could add another node:您可以添加另一个节点:

int main( void )
{
  List *l = newList();
  insertNode( l, 5 );
  insertNode( l, 3 );
  ...
}

then your picture becomes那么你的照片就变成了

+---------+       +--------------------+      +------------+        +------------+
| l: addr | ----> | head: addr         | ---> | data: 5    |   +--> | data: 3    |
+---------+       +--------------------+      +------------+   |    +------------+
                  | number_of_nodes: 2 |      | link: addr | --+    | link: NULL |
                  +--------------------+      +------------+        +------------+

Naturally, you'd want to add some error checking and messages in case a node couldn't be allocated (it happens).自然地,您会想要添加一些错误检查和消息,以防节点无法分配(发生这种情况)。 And you'd probably want an ordered list, where elements are inserted in order (ascending, descending, whatever).而且您可能想要一个有序列表,其中元素按顺序插入(升序、降序等)。 But this should give you a flavor of how to build lists.但这应该让您了解如何构建列表。

You'd also need functions to remove items and free that memory.您还需要删除项目并释放内存的函数。 Here's how I'd free an entire list:这是我释放整个列表的方法:

void freeList( List *l )
{
  Node *prev, *cur = l->head;
  while( cur && cur->link )
  {
    prev = cur;
    cur = cur->link;
    free( prev );
  }
  free( cur );
}

int main( void )
{
  List *l = newList();
  ...
  freeList( l );
  free( l );
  ...
}

… a pointer of a type struct… ... 类型结构的指针 ...

A pointer cannot be of a type struct.一个指针不能是结构类型 A pointer can point to a structure.指针可以指向的结构。

C has objects. C 有对象。 Objects include char , int , double , structures, and other things.对象包括charintdouble 、结构和其他东西。 A structure is a collection of objects grouped together.结构是组合在一起的对象的集合。

In main, if you define p with Node *p;在主,如果定义pNode *p; , you then have a pointer p . ,然后你有一个指针p It has no value because you have not given it a value.它没有价值,因为你没有给它一个价值。 When you execute p = malloc(sizeof *p);当你执行p = malloc(sizeof *p); , you request enough memory for the size of the thing p points to ( *p ). ,您为p指向的事物 ( *p ) 的大小请求足够的内存。 If malloc returns a non-null pointer, then p points to a Node structure.如果malloc返回一个非空指针,则p指向一个Node结构。

Then p->data refers to the data member of that structure.然后p->data指的是该结构的data成员。 p->data is shorthand for (*p).data , in which *p means “the object p points to” and .data means “the data member in that object.” p->data(*p).data简写,其中*p表示“对象p指向”,而.data表示“该对象中的data成员”。

After p = malloc(sizeof *p);p = malloc(sizeof *p); and p->data = 5;并且p->data = 5; , p->link does not point to anything because you have not assigned it a value. , p->link不指向任何东西,因为你没有给它赋值。 In a linked list, you would use malloc to get memory for another Node , and then you would set the p->link in one Node to point to the new Node .在链表中,您将使用malloc为另一个Node获取内存,然后将一个Nodep->link设置为指向新Node In each Node , its link member points to the next Node in the list.在每个Node ,它的link成员指向列表中的下一个Node Except, in the last Node , p->link is set to a null pointer to indicate it is the last Node .除了在最后一个Nodep->link设置为空指针以指示它是最后一个Node

In List , you would set head to point to the first Node in a list of Node objects.List中,您将设置head以指向第一个Node中的一个列表Node对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM