簡體   English   中英

推進鏈表中的指針

[英]advancing pointer in a linked list

我正在嘗試創建一個函數來將鏈表中的當前指針前進到列表中的下一個實體。 這是我的列表結構;

    * malloc() a new list header and initialize it */
list_t *list_init(void)
{
    list_t *list = (list_t *)malloc(sizeof(list_t));
      list->first = NULL;            
          list->last = NULL; 
      list->current = NULL; 
return list;      
}

這是我的鏈接結構

    /* add an element to the end of a list */
void list_add(list_t *list, void *entity)
{
    link_t *link = (link_t *)malloc(sizeof(link_t));       
         link->entity = (link_t *)entity; 
     //link->next = (link_t *)list;  
       if(list->first != NULL){
            list->last = link;
            link->next = NULL;
            list->last->next = list->current;
            list->current = list->last;
       }        
               else { 

               list->first = link->entity;  }
}

這是我正在嘗試創建的函數,我在使它進入下一個實體時遇到問題

/* advance current pointer to next link */
void list_next_link(list_t *list)
{

   assert(list->current != NULL);

    list->last->next = list->current;
    list->last->next =list->current->entity;
    list->current = NULL;   

}

我不確定我應該如何讓它前進到下一個鏈接; 第一個條目打印正常,其余條目看起來像是在有分段錯誤之前從隨機內存地址打印。

如果您的列表被設計為“實體”對象的容器,就像您從添加功能中看到的那樣,那么我很快就會看到兩個問題。 首先,實體數據類型應完全獨立於列表數據類型,因此將其強制轉換為list_add中的link_t *是錯誤的,最多會令人困惑。 這可能是第二個問題的根源:列表中的下一個指針不應指向“實體”對象。 “next”指針應該只指向使用list_add創建的列表中的有效項。 我沒有詳細你的list_next_link是為了做研究,但它幾乎肯定是錯誤的覆蓋與列表中所含值“下一個”指針。 重新解釋列表項中的任何數據作為列表指針必然會導致問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM