8

I would like to know if there is any way by which I can create dynamically sized array to avoid runtime error in the code below.

Error:

panic: runtime error: index out of range in Go

Code:

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func nextLargerNodes(head *ListNode) []int {

    var a []int
    var pha int
    hNum := 0
    currNode := head
    pha = 0
    for currNode.Next != nil {
        iter := currNode.Next
        hNum = currNode.Val
        //phb = pha + 1
        for(iter.Next != nil){
            if hNum < iter.Val {
                hNum = iter.Val
                break
            } else if hNum == iter.Val{
                hNum = 0
                break
            }

            iter = iter.Next
        }
        a[pha] = iter.Val
        pha++
        hNum = 0
        currNode = currNode.Next
    }
    return a
}
Gustavo Pagani
  • 6,583
  • 5
  • 40
  • 71
Rohit Parab
  • 111
  • 1
  • 1
  • 2
  • I retracted my flag, but here's something perhaps more helpful: https://stackoverflow.com/questions/3387273/how-to-implement-resizable-arrays-in-go – hugo Aug 10 '19 at 11:37
  • `a = append(a, iter.Val)` and you don't need `pha` any more. – Henry Aug 10 '19 at 11:44
  • 1
    1. No, there's no such thing as a dynamically sized array in Go. 2. You're not using an array at all. You're using a slice. 3. Slices _are_ dynamically sized. – Jonathan Hall Aug 10 '19 at 13:39
  • 1
    https://tour.golang.org/moretypes/15 – Peter Aug 10 '19 at 13:55

2 Answers2

12

You should use append function.

var a []int

is a slice, you can think of it as a "dynamic array". In order to add elements to it, you should use append method. In your code, you used array semantics.

a = append(a, iter.Val)

You can create your slice with a predefined number of elements if you know upfront how many elements you are going to have in your slice.

a := make([]int, 10)

this will create a slice with 10 elements in it.

Vlad Bezden
  • 83,883
  • 25
  • 248
  • 179
6

Go arrays are fixed in size, but thanks to the builtin append method, we get dynamic behavior. The fact that append returns an object, really highlights the fact that a new array will be created if necessary. The growth algorithm that append uses is to double the existing capacity.

numbers := make([]int, 0)
numbers = append(numbers, 1)
numbers = append(numbers, 2)
fmt.Println(len(numbers)) // == 2
Surjit R
  • 315
  • 1
  • 5