jjzjj

go - panic : runtime error: invalid memory address or nil pointer dereference [signal 0xc0000005 code=0x0 addr=0x8 pc=0x48be5c] goroutine 1 [running]:

coder 2024-07-14 原文

我正在尝试使用链表实现多项式的加法。该程序成功地添加了幂 0 系数,但在第一次遍历后它出现了困惑。这是我到目前为止编写的代码。在初始化 temp1!= nil 之后,循环遍历 else 但当权力不同时不进入 if 循环并进入 panic 状态

package main

import (
    "fmt"
)

type Node struct {
    coefficient int
    power       int
    next        *Node
}

type list struct {
    head  *Node
    count int
}

func main() {
    list1 := &list{}
    list1.addVariable(5, 2)
    list1.addVariable(4, 1)
    list1.addVariable(3, 0)
    list1.print()
    list2 := &list{}
    list2.addVariable(4, 1)
    list2.addVariable(2, 0)
    list2.print()
    list4 := addLists(list1, list2)
    list4.print()

}

func (lst *list) print() {
    temp := lst.head
    for temp != nil {
        fmt.Print(temp.coefficient, "x", "^", temp.power, "+")
        temp = temp.next
    }
    fmt.Println("\n")
}

func (lst *list) addVariable(coefficient int, power int) {
    lst.head = &Node{coefficient, power, lst.head}
    lst.count++
}

func addLists(list1 *list, list2 *list) *list {
    list3 := &list{}
    temp1 := list1.head
    temp2 := list2.head
    fmt.Println("reached") // for debugging purposes
    if list1.count > list2.count {
        fmt.Println("\nreached 2") // for debugging purposes
        for temp1 != nil {
            fmt.Println("reached3") // for debugging purposes
            if temp1.power != temp2.power {
                fmt.Println("reached4") // for debugging purposes
                list3.normalAdd(temp1, temp2)
                temp1 = temp1.next

            } else {
                fmt.Println("reached5") // for debugging purposes
                node4 := add(temp1, temp2)
                list3.exlusiveAdd(node4)
                temp1 = temp1.next
                temp2 = temp2.next
            }
        }
    }
    return list3
}

func (lst *list) normalAdd(node6 *Node, node7 *Node) {
    node6.next = lst.head
    lst.head = node6
    node7.next = lst.head
    lst.head = node7
    lst.count += 2
}

func (lst *list) exlusiveAdd(node5 *Node) {
    node5.next = lst.head
    lst.head = node5
    lst.count++
}

func add(node1, node2 *Node) *Node {
    node3 := &Node{}
    node3.coefficient = node1.coefficient + node2.coefficient
    node3.power = node1.power
    return node3
}

程序运行时的输出:

3x^0+4x^1+5x^2+
2x^0+4x^1+
reached

reached 2
reached3
reached5
reached3
reached5
reached3
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0xffffffff addr=0x0 pc=0xd48e6]

goroutine 1 [running]:
main.addLists(0x41c7a8, 0x41c7a0, 0x40c120, 0x1d)
    /tmp/sandbox520212269/main.go:56 +0x186
main.main()
    /tmp/sandbox520212269/main.go:28 +0x220

Playground here

更新:感谢您的解决方案,但我已经成功编写了上述问题的代码。这里是。 包主

import (
"fmt"
)

type Node struct {
coefficient int
power       int
next        *Node
}

type list struct {
head  *Node
count int
}

func main() {
list1 := &list{}
list1.addVariable(5, 2)
list1.addVariable(4, 1)
list1.addVariable(3, 0)
list1.print()
list2 := &list{}
list2.addVariable(4, 1)
list2.addVariable(2, 0)
list2.print()
poly := addPoly(list1, list2)
poly.print()
}

func (lst *list) print() {
temp := lst.head
for temp != nil {
    fmt.Print(temp.coefficient, "x", "^", temp.power, "+")
    temp = temp.next
}
fmt.Println("\n")
}

func (lst *list) addVariable(coefficient int, power int) {
lst.head = &Node{coefficient, power, lst.head}
lst.count++
}

func addPoly(list_1 *list, list_2 *list) *list {
list_3 := &list{}
temp_1 := list_1.head
temp_2 := list_2.head
if list_1.count > list_2.count {
    for temp_1 != nil && temp_2 != nil {
        if temp_1.power == temp_2.power {
            new_coefficient := temp_1.coefficient + temp_2.coefficient
            new_power := temp_1.power
            list_3.addVariable(new_coefficient, new_power)
            temp_1 = temp_1.next
            temp_2 = temp_2.next
        } else if temp_1.power != temp_2.power {
            list_3.addVariable(temp_1.coefficient, temp_1.power)
            list_3.addVariable(temp_2.coefficient, temp_2.power)
            temp_1 = temp_1.next
            temp_2 = temp_2.next
        }
    }
}
for temp_1 != nil {
    list_3.addVariable(temp_1.coefficient, temp_1.power)
    temp_1 = temp_1.next
}
return list_3
}

最佳答案

错误发生是因为您试图在下面的代码中从 nil 对象访问 .power 属性。 temp1temp2 都是 nil

if temp1.power != temp2.power {
   // ...
}

list 结构上的.head 属性具有指针数据类型。指针数据类型的零值是nil。在您的代码中,list1list2.head 属性都具有 nil 值。

您需要做的:在创建 list1list2 期间明确初始化 .head 属性的值。然后 panic 错误将消失,您的代码将正常工作。

list1 := &list{head: new(Node)}
// ...
list2 := &list{head: new(Node)}
// ...

Playground :https://play.golang.org/p/vPK3pYKht3E

关于go - panic : runtime error: invalid memory address or nil pointer dereference [signal 0xc0000005 code=0x0 addr=0x8 pc=0x48be5c] goroutine 1 [running]:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53424273/

有关go - panic : runtime error: invalid memory address or nil pointer dereference [signal 0xc0000005 code=0x0 addr=0x8 pc=0x48be5c] goroutine 1 [running]:的更多相关文章

  1. ruby - 在 Ruby 程序执行时阻止 Windows 7 PC 进入休眠状态 - 2

    我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0

  2. 电脑0x0000001A蓝屏错误怎么U盘重装系统教学 - 2

      电脑0x0000001A蓝屏错误怎么U盘重装系统教学分享。有用户电脑开机之后遇到了系统蓝屏的情况。系统蓝屏问题很多时候都是系统bug,只有通过重装系统来进行解决。那么蓝屏问题如何通过U盘重装新系统来解决呢?来看看以下的详细操作方法教学吧。  准备工作:  1、U盘一个(尽量使用8G以上的U盘)。  2、一台正常联网可使用的电脑。  3、ghost或ISO系统镜像文件(Win10系统下载_Win10专业版_windows10正式版下载-系统之家)。  4、在本页面下载U盘启动盘制作工具:系统之家U盘启动工具。  U盘启动盘制作步骤:  注意:制作期间,U盘会被格式化,因此U盘中的重要文件请注

  3. ruby-on-rails - 如何解决#<Book::ActiveRecord_Relation:0x007fb709a6a8c0> 的未定义方法 `to_key'? - 2

    我遇到了未定义方法`to_key'的问题这是我的books_controller.rbclassBooksController和我的索引页如下。index.html.erb......现在当我要访问索引页面时出现如下错误。undefinedmethod`to_key'for# 最佳答案 index通常返回一个集合。事实上,您的Controller符合要求。但是,您的View试图为其定义一个表单。正如您所发现的,这不会成功。表单适用于实体,而不适用于集合。该错误在您看来以及您希望如何处理index。

  4. ruby-on-rails - Rspec - Controller 测试错误 - Paperclip::AdapterRegistry::NoHandlerError: 找不到 "#<File:0x531beb0>"的处理程序 - 2

    我如下询问了我的Rspec测试。Rspec-RuntimeError:Calledidfornil,whichwouldmistakenlybe4在相同的代码上(“items_controller.rb”的Rspec测试),我试图对“PUTupdate”进行测试。但是我收到错误消息“Paperclip::AdapterRegistry::NoHandlerError:找不到“#”的处理程序。我的Rspec测试如下。老实说,我猜这次失败的原因是“let(:valid_attributes)”上的“photo”=>File.new(Rails.root+'app/assets/images

  5. ruby - session 未创建 : Chrome version must be between - 2

    当使用ruby​​selenium驱动程序驱动chrome时,我得到/home/travis/.rvm/gems/ruby-2.6.2/gems/selenium-webdriver-3.141.5926/lib/selenium/webdriver/remote/response.rb:72:in`assert_ok':sessionnot创建:Chrome版本必须在70和73之间(Selenium::WebDriver::Error::SessionNotCreatedError)如何解决这个问题?降级chrome不是我想做的事。 最佳答案

  6. ruby-on-rails - `method_missing':#<Rails::Application::Configuration:0x00> 的未定义方法 `action_mailer' - 2

    我正在构建一个Rails应用程序并且使用的是Rails4.0.1。我有一个错误,并注意到它在3个月前被称为rails上的一个错误,所以我决定:捆绑更新并获得rails4.0.3这样做之后,测试和服务器都不会启动,并且会抛出错误:gems/railties-4.0.3/lib/rails/railtie/configuration.rb:95:in`method_missing':undefinedmethod`action_mailer'for#(NoMethodError)目前我在config/environments/*中注释掉了action_mailer行,但最好能找到一个真正的

  7. ruby-on-rails - 为什么 ruby​​-debug 说 'Saved frames may be incomplete' - 2

    我有时会在触发断点时收到此消息。看起来堆栈帧没有得到保存,所以我无法通过调用堆栈返回-真的很痛苦。看下面的例子-->#0BatchProcess.add_failure_record(row_id#Fixnum,test#Struct::Test,message#String,...)atlineserver/processes/batch.rb:309Warning:savedframesmaybeincomplete;comparewithcaller(0).(rdb:1)ppcaller["./server/processes/batch.rb:309:in`run_tests'

  8. ruby-on-rails - #<ProjectsController :0x007faead1853e0> 的未定义方法 `user_signed_in?' - 2

    我想用RubyonRails进行身份验证,每个用户都有自己的帐户。但是现在我得到了这个错误:undefinedmethoduser_signed_in?for#有人能帮帮我吗?代码如下:完整跟踪:app/controllers/projects_controller.rb:69:in`require_login'activesupport(3.2.3)lib/active_support/callbacks.rb:418:in`_run__2505248868868045404__process_action__114470166732456289__callbacks'actives

  9. ruby - 杰基尔 : New posts not being generated - 2

    我正在建立一个jekyll博客。我将.md文件放在_posts文件夹中。在项目根目录下运行jekyll--server命令。但是jekyll只是重新生成旧帖子,新闻帖子不会添加到_site。可能是什么问题? 最佳答案 我终于找到了jekyll失败的原因。我在我的一篇帖子中使用的标题中有一个冒号(:)。我只需要用:替换它并且帖子解析得很好。 关于ruby-杰基尔:Newpostsnotbeinggenerated,我们在StackOverflow上找到一个类似的问题:

  10. ruby - Chef : Can a variable set within one ruby_block be used later in a recipe? - 2

    假设我有一个变量directory_list,我在名为get_directory_list的ruby​​_block中定义和设置了它。我可以稍后在我的Recipe中使用directory_list吗,或者编译/收敛过程会阻止这种情况吗?例子:ruby_block"get_file_list"doblockdotransferred_files=Dir['/some/dir/*']endendtransferred_files.eachdo|file|file"#{file}"dogroup"woohoo"user"woohoo"endend 最佳答案

随机推荐