亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

存在與無效內存訪問相關的錯誤

存在與無效內存訪問相關的錯誤

Go
慕標琳琳 2022-12-19 10:45:58
GO 世界中的綠色環境 - 事實上,這是我在 GO 中的第一個程序。我正在編寫一個反轉鏈表的算法,特別是來自這個leetcode。下面的代碼片段沒有公開我的算法,只公開了我main()用來測試我的實現的函數。調試后,我發現我在此處箭頭處失敗,并顯示錯誤信息panic: runtime error: invalid memory address or nil pointer dereference。type ListNode struct {    Val int    Next *ListNode}func main(){    var list *ListNode    head := list    for i := 0; i <= 5; i++ {        var dummy *ListNode        list.Val = i    <--------------------- here        list.Next = dummy        dummy = list    }    result := reverseList(head)    for result != nil{        fmt.Printf("%d\t", result.Val)    }}我真的很感激對這個問題的一些討論!
查看完整描述

2 回答

?
肥皂起泡泡

TA貢獻1829條經驗 獲得超6個贊

基本問題是您永遠不會為結構指針分配內存。當你寫:


var list *ListNode

您已經創建了一個指向 ListNode 類型的指針,但您實際上并沒有為它分配任何內存。所以當你嘗試寫...


list.Val = i

您收到“無效內存地址”錯誤,因為您試圖取消引用未定義的指針。分配內存的一種方法是使用new()新的內置函數:


var list *ListNode = new(ListNode)

您還可以獲取結構的地址,如下所示:


list := &ListNode{}

上面顯示了正確的語法,但是如果您只是用var上面的聲明替換現有的聲明,您的代碼中仍然會有邏輯問題:您不想分配任何內存,直到您將第一個節點添加到列表中。這意味著我們要等到我們進入for循環內才能分配內存。


通過對您的代碼進行一些小的更改,我們得到:


package main


import "fmt"


type ListNode struct {

    Val  int

    Next *ListNode

}


func main() {

    var head, tail *ListNode


    for i := 0; i <= 5; i++ {

        node := new(ListNode)

        node.Val = i


        if tail == nil {

            // This is the first node in the list, so just point head

            // and tail at the new node.

            tail = node

            head = tail

        } else {

            // There is at least one node in the list, so attach the new

            // node to the tail

            tail.Next = node

            tail = node

        }

    }


    result := head


    for result != nil {

        fmt.Printf("%d\t", result.Val)


        // Don't forget to increment to the next node!

        result = result.Next

    }

}

運行此代碼會產生:


0       1       2       3       4       5


查看完整回答
反對 回復 2022-12-19
?
慕桂英4014372

TA貢獻1871條經驗 獲得超13個贊

您必須為列表節點分配內存。創建列表節點時,更新前一個節點中的 Next 字段或更新列表頭(如果這是第一個節點)。


var head *ListNode


// p is pointer to head or pointer to previous node's Next.  

// We start with p set as pointer to the head.

p := &head


for i := 0; i <= 5; i++ {

    // Allocate a new ListNode with Val initialized.

    n := &ListNode{Val: i}


    // Update head or previous node'a Next field.

    *p = n


    // The next iteration of the loop should update

    // the Next field in the node that we just created.

    p = &n.Next

}


// Loop while list node is not nil.

for n := head; n != nil; n = n.Next {

    fmt.Println(n.Val)

}

    

https://go.dev/play/p/qUhza05kUFT


查看完整回答
反對 回復 2022-12-19
  • 2 回答
  • 0 關注
  • 161 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號